How to draw on top of a TextBox

2019-02-16 00:23发布

I have winform with a TextBox and I want to draw some GDI graphics on top of it. The text box does not have a Paint() event to hook to, so I assume it all has to happeen within the form's Paint event. As a test I am drawing a rectangle from the origin to a location within the text box with:

    private void FindForm_Paint(object sender, PaintEventArgs e)
    {
        using (Pen pen = new Pen(Color.Blue))
        {
            e.Graphics.DrawRectangle(pen, 0, 0, point.X, point.Y);
        }
    }

The problem is that when I run, the drawing is done first, and then the text box is rendered, on top of my lines. I want to draw the lines after the text box is rendered.

PS. I have not made any settings for the form with the Form.SetStyle() function.

2条回答
时光不老,我们不散
2楼-- · 2019-02-16 00:50

The System.Windows.Forms.TextBox class does have a Paint event: http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.paint.aspx. According to the MSDN it is not intended to be used in your code, but you might not have any other option if you do not want to create your own control using inheritance.

If you want to draw inside the TextBox you should use its Paint and a Graphics object created from its handle. If you draw using the Form's Paint even, when the TextBox receives its own Paint event it will override the previous draw since the TextBox is on top of the Form.

If you are not using the Paint event of the TextBox, you can still get its Graphics object using the CreateGraphics method. However, you will have to be careful to do your drawing after the TextBox's Paint event, otherwise it might get overridden.

In the end you might need to create your own control inheriting from TextBox. Inheritance is a powerful method of overriding default behavior in Windows Forms programming.

Please let me know if you need additional help.

查看更多
\"骚年 ilove
3楼-- · 2019-02-16 00:55

It can be relatively tricky to owner-draw the TextBox control because it's simply a wrapper around the native Win32 TextBox control.

The easiest way to capture the WM_PAINT messages that you need to handle for your custom painting routines to work is by inheriting from the NativeWindow class.

Here is an excellent step-by-step article that shows how to do this in the context of displaying the red wavy underlines: Owner-drawing a Windows.Forms TextBox (original link dead; replaced by archived version)

查看更多
登录 后发表回答