【C#】Winform界面防止闪烁
1. Form界面
1 protected override CreateParams CreateParams 2 { 3 get 4 { 5 CreateParams cp = base.CreateParams; 6 cp.ExStyle |= 0x02000000; // Turn on WS_EX_COMPOSITED 7 if (this.IsXpOr2003 == true) 8 { 9 cp.ExStyle |= 0x00080000; // Turn on WS_EX_LAYERED 10 this.Opacity = 1; 11 } 12 return cp; 13 } 14 } //防止闪烁 15 16 private Boolean IsXpOr2003 17 { 18 get 19 { 20 OperatingSystem os = Environment.OSVersion; 21 Version vs = os.Version; 22 if (os.Platform == PlatformID.Win32NT) 23 if ((vs.Major == 5) && (vs.Minor != 0)) 24 return true; 25 else 26 return false; 27 else 28 return false; 29 } 30 }
2. UserControls界面
1 public class NoFlickerUserControl : UserControl 2 { 3 public NoFlickerUserControl() 4 { 5 this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); 6 this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); 7 this.SetStyle(ControlStyles.UserPaint, true); 8 this.UpdateStyles(); 9 } 10 11 protected override void OnHandleCreated(EventArgs e) 12 { 13 base.OnHandleCreated(e); 14 if (IsXpOr2003) 15 { 16 // 请注意,Opacity不适用于UserControl,这里不需要处理 17 int exStyle = NativeMethods.GetWindowLong(this.Handle, NativeMethods.GWL_EXSTYLE); 18 exStyle |= 0x02000000; // WS_EX_COMPOSITED 19 NativeMethods.SetWindowLong(this.Handle, NativeMethods.GWL_EXSTYLE, exStyle); 20 } 21 } 22 23 private bool IsXpOr2003 24 { 25 get 26 { 27 OperatingSystem os = Environment.OSVersion; 28 Version vs = os.Version; 29 return os.Platform == PlatformID.Win32NT && (vs.Major == 5 && vs.Minor != 0); 30 } 31 } 32 33 private static class NativeMethods 34 { 35 public const int GWL_EXSTYLE = -20; 36 37 [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] 38 public static extern int GetWindowLong(IntPtr hWnd, int nIndex); 39 40 [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] 41 public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); 42 } 43 }
3. UserControls界面-新写法
1 public class NoFlickerUserControl : UserControl 2 { 3 public NoFlickerUserControl() 4 { 5 SetStyle(ControlStyles.OptimizedDoubleBuffer | 6 ControlStyles.AllPaintingInWmPaint | 7 ControlStyles.UserPaint, true); 8 UpdateStyles(); 9 } 10 11 protected override CreateParams CreateParams 12 { 13 get 14 { 15 CreateParams cp = base.CreateParams; 16 cp.ExStyle |= 0x02000000; // WS_EX_COMPOSITED 17 return cp; 18 } 19 } 20 }
时间:2025年3月14日

Winform界面防止闪烁
浙公网安备 33010602011771号