Natrium
Natrium

Reputation: 31174

How to give a textbox a fixed width of 17,5 cm?

I have an application with a textbox, and the width of the textbox on the screen must always be 17,5 centimeters on the screen of the user.

This is what I tried so far:

const double centimeter = 17.5; // the width I need
const double inches = centimeter * 0.393700787; // convert centimeter to inches

float dpi = GetDpiX(); // get the dpi. 96 in my case.

var pixels = dpi*inches; // this should give me the amount of pixels
textbox1.Width = Convert.ToInt32(pixels); // set it. Done.



private float GetDpiX()
{
    floar returnValue;
    Graphics graphics = CreateGraphics();
    returnValue = graphics.DpiX;
    graphics.Dispose(); // don’t forget to release the unnecessary resources
    return returnValue;
}

But this gives me different sizes with different resolutions.

It gives me 13 cm with 1680 x 1050 and 21,5 cm with 1024 x 768.

What am I doing wrong?

Upvotes: 9

Views: 2318

Answers (3)

Mark Menchavez
Mark Menchavez

Reputation: 1661

Width property of the Size structure depend on PageUnit and PageScale settings of the Graphics class. Try playing around with these settings to get your desired effect. Since you most likely need to modify these settings on the Paint event of the control, I suggest you create your own custom TextBox control instead.

Upvotes: 0

Xenan
Xenan

Reputation: 543

The method graphics.DpiX does not give the real dots per inch of the monitor. It returns the DPI set in Windows Display properties, mostly either 96 or 120 DPI.

It is not possible to read the real DPI of the monitor. Microsoft did research this for Windows Vista/7 but as long as manufactures of monitors do not provide a standard way to read the value from the monitor hardware it will not be possible.

Upvotes: 7

digEmAll
digEmAll

Reputation: 57210

Yes, unfortunately Xenan is right. To workaround the problem you could allow a sort of by hand calibration, done by the user.

e.g. draw a line of 400 pixel on the screen, ask the user to measure it on the screen and set the result. Now is really simple to calculate the PPI (pixels per inch) that is your calibration.

Upvotes: 3

Related Questions