[英]why my custom control textbox's onpaint overided method never gets called?
我創建了一個帶有紅色邊框的自定義文本框。 然后,我啟動我的應用程序,但是此OnPaint從未被調用。
我的代碼是這樣的:
public partial class UserControl1 : TextBox
{
public string disable, disableFlag;
public string Disable
{
get
{
return disable;
}
set
{
disable = value;
disableFlag = disable;
//OnPaint(PaintEventArgs.Empty);
}
}
public UserControl1()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
this.Text = "testing 1";
if (disable == "true")
{
Pen redPen = new Pen(Color.Red);
Graphics graphics = this.CreateGraphics();
graphics.DrawRectangle(redPen, this.Location.X,
this.Location.Y, this.Width, this.Height);
// base.DrawFrame(e.Graphics);
}
}
}
請讓我知道問題出在哪里(這是winform的快照http://prntscr.com/ceq7x5 )?
您不應該創建一個新的Graphics對象。 使用e.Graphics.DrawRectangle
可以使用已經存在的Graphics對象在控件上進行繪制,如下所示:
Pen redPen = new Pen(Color.Red);
e.Graphics.DrawRectangle(redPen, this.Location.X,
this.Location.Y, this.Width, this.Height);
另外,在這里重復我關於“禁用”標志的評論。 沒有必要添加自定義“禁用”標志。 使用Windows窗體TextBox控件已經提供的Enabled屬性。
編輯:請注意,以上代碼在TextBox的情況下不起作用,因為它以不同的方式處理繪圖。 基本上,TextBox只是本機Win32 TextBox的包裝,因此您需要聆聽一些告訴其重新繪制自身的消息。 您還需要獲取設備上下文的句柄,並將其轉換為托管Graphics對象才能繪制。
查看本文,獲取有關如何在TextBox上繪制的代碼和說明。 特別是第2部分。繪制到頁面底部的TextBox上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.