[英]Drawing rectangle over a textbox
我的問題是,我想在現有的文本框上繪制一個矩形。
我現在有一個解決方案,但文本框總是重繪,這是我不想要的行為。
這是代碼
private bool isDragging = false;
void Form2_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
endPos = e.Location;
Rectangle rect;
if (endPos.Y > startPos.Y)
{
rect = new Rectangle(startPos.X, startPos.Y,
endPos.X - startPos.X, endPos.Y - startPos.Y);
}
else
{
rect = new Rectangle(endPos.X, endPos.Y,
startPos.X - endPos.X, startPos.Y - endPos.Y);
}
Region dragRegion = new Region(rect);
this.Invalidate();
}
}
void Form2_MouseUp(object sender, MouseEventArgs e)
{
isDragging = false;
this.Invalidate();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp;
cp = base.CreateParams;
cp.Style &= 0x7DFFFFFF; //WS_CLIPCHILDREN
return cp;
}
}
void Form2_MouseDown(object sender, MouseEventArgs e)
{
isDragging = true;
startPos = e.Location;
}
// this is where we intercept the Paint event for the TextBox at the OS level
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 15: // this is the WM_PAINT message
// invalidate the TextBox so that it gets refreshed properly
Input.Invalidate();
// call the default win32 Paint method for the TextBox first
base.WndProc(ref m);
// now use our code to draw extra stuff over the TextBox
break;
default:
base.WndProc(ref m);
break;
}
}
protected override void OnPaint(PaintEventArgs e)
{
if (isDragging)
{
using (Pen p = new Pen(Color.Gray))
{
p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
e.Graphics.DrawRectangle(p,
startPos.X, startPos.Y,
endPos.X - startPos.X, endPos.Y - startPos.Y);
}
}
base.OnPaint(e);
}
這里的問題是,文本框是閃爍的,完成拖動后矩形沒有設置在文本框的前面。
我該如何解決這個問題?
你正在關閉標志: WndProc
WS_CLIPCHILDREN
。
WS_CLIPCHILDREN
值為0x02000000
,您將在代碼中將其關閉:
cp.Style &= 0x7DFFFFFF; //WS_CLIPCHILDREN
WS_CLIPCHILDREN
標志默認設置,它可以防止子控件的閃爍。 如果您不關閉標志,則閃爍將停止。
根據WS_CLIPCHILDREN上的文檔:在父窗口中進行繪制時,排除子窗口占用的區域。 創建父窗口時使用此樣式。
側注 :關閉標志時,使用要關閉的標志值更清楚:
cp.Style &= ~0x02000000; //WS_CLIPCHILDREN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.