How to draw on top of a TextBox

后端 未结 2 945
死守一世寂寞
死守一世寂寞 2021-01-03 17:39

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 t

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 18:28

    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.

提交回复
热议问题