以下代码用于将控件禁用但不改变控件样式(字体颜色等)
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int wndproc);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
public const int GWL_STYLE = -16;
public const int WS_DISABLED = 0x8000000;
public static void SetControlEnabled(Control c, bool enabled)
{
if (enabled)
{ SetWindowLong(c.Handle, GWL_STYLE, (~WS_DISABLED) & GetWindowLong(c.Handle, GWL_STYLE)); }
else
{ SetWindowLong(c.Handle, GWL_STYLE, WS_DISABLED + GetWindowLong(c.Handle, GWL_STYLE)); }
}
private void button2_Click(object sender, System.EventArgs e)
{
SetControlEnabled(this.button1, false);
this.button1.ForeColor = Color.White;
}
但在实际中发现,在反复将控件设为false后,再将控件设为true却没有用了
这里对上述做个修正,false的情况下
SetWindowLong(c.Handle, GWL_STYLE, WS_DISABLED + GetWindowLong(c.Handle, GWL_STYLE));
这句代码把“+”改成“|”比较好,不会造成反复false而导致窗口出错。
特此记录下来,方便自己也方便大家。
本文介绍了一个在Windows窗体应用程序中修改控件禁用状态而不改变其外观样式的技巧。通过使用SetWindowLong函数并正确应用WS_DISABLED样式标志,可以避免多次禁用控件导致的界面错误。文章提供了具体的代码示例,并指出在设置控件为禁用状态时,使用“|”操作符优于“+”,以防止窗口出现异常。
2589

被折叠的 条评论
为什么被折叠?



