C#winform中,我想点击button1就将txt2的边框颜色改变,下面的代码可以实现:

2024-11-07 21:05:35
推荐回答(2个)
回答(1):

private static int WM_NCPAINT = 0x0085;
private static int WM_ERASEBKGND = 0x0014;
private static int WM_PAINT = 0x000F;

[DllImport("user32.dll")]
static extern IntPtr GetDCEx(IntPtr hwnd, IntPtr hrgnclip, uint fdwOptions);

[DllImport("user32.dll")]
static extern int ReleaseDC(IntPtr hwnd, IntPtr hDC);

protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_NCPAINT || m.Msg == WM_ERASEBKGND || m.Msg == WM_PAINT)
{
IntPtr hdc = GetDCEx(m.HWnd, (IntPtr)1, 1 | 0x0020);

if (hdc != IntPtr.Zero)
{
Graphics graphics = Graphics.FromHdc(hdc);
Color borderColor = Color.HotPink;

Rectangle rectangle = new Rectangle(textBox1.Location.X, textBox1.Location.Y + (25), textBox1.Width, textBox1.Height);
ControlPaint.DrawBorder(graphics, rectangle, borderColor, ButtonBorderStyle.Solid);
m.Result = (IntPtr)1;
ReleaseDC(m.HWnd, hdc);

}
}
}

------------------------------------------
用这种,不会闪,需要把textbook的边框去掉,Border设置为None。 然后自己调一下位置与宽度吧。

回答(2):

加上这段
private void txt2_Click(object sender, EventArgs e)
{
this.txt2_Paint(sender, new PaintEventArgs(this.txt2.CreateGraphics(), txt2.ClientRectangle));
}
不过这样当鼠标点击txt2的时候 边框会闪动一下、、