Using Graphics.DrawString to Simulate a TextBox Rendering

I have a C # UserControl that hosts a TextBox.

When the user control is disabled, I would like the TextBox to appear as if it was disabled + ReadOnly (i.e. not grayed out). Therefore, when a user control catches EnabledChanged, it sets the placed TextBox properties appropriately.

However, the Enabled state with UserControl takes precedence over everything else, and the TextBox is still grayed out (although its internal ForeColor is correct).

So I decided to hide the hosted TextBox when the user control was disabled and drew it myself. I can successfully display the TextBox frame using various ControlPaint.DrawXxx functions.

However, when you draw text, you get a stretched output compared to your own rendering. That is, the text starts at the same pixel location, but the distance between the characters is noticeably greater.

I use my own TextBox font to render, so I don't know what I'm doing wrong. The only excuse I can make is that the C # TextBox is displayed directly by Windows (using the ExtTextOut Win32 API), and this leads to obvious differences.

What options can I use to simulate TextBox's own rendering?

0
source share
1 answer

The difference is that Graphics.DrawString uses GDI + to render text, while the Win32 API uses GDI internally for everything, including drawing text on controls.

Starting with .NET 2.0 , you can easily simulate its appearance using TextRenderer.DrawText , which also uses GDI for drawing.

In most cases, replacing Graphics.DrawString with TextRenderer.DrawText is simple. You are not showing any code, so it is difficult to specify a specific example.


As for why you should do this in the first place ... Disabling container management always disables all child controls. This is a tough rule in Windows with no exceptions. Of course, this is pretty reasonable.
If you do not want all controls inside the container to be disabled, you should not disable the entire container - just disable individual controls inside this container.

Even if you have a slightly better way to text, I still highly recommend that you not try and TextBox control. This is a rather difficult job, and it is unlikely that you can handle it in just a few days / weeks of effort.

+2
source

Source: https://habr.com/ru/post/1241964/


All Articles