我有一个大面板,里面有很多子面板。这些子面板内部有两个具有透明背景的文本字段。它本质上是从头开始构建的 ListBox。
我想做的是循环遍历每个子面板,并在用户单击其中一个时将其背景颜色更改为选定的颜色。
但是,当我单击新的子面板时,旧背景颜色和新背景颜色之间有非常明显的闪烁。
注意:当用户将鼠标悬停在面板上时,浅蓝色是突出显示的颜色。
我尝试将主面板和表单本身的 DoubleBuffered 设置为 true,但运气不佳。我也尝试将 ControlStyles.AllPaintingInWmPaint、ControlStyles.UserPaint 和 ControlStyles.OptimizedDoubleBuffer 设置为 true。
public class List : Panel
{
private Panel[] items;
private Label[] header; // Children of items
private Label[] footer; // Children of items
public List()
{
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
AutoScroll = true;
BackColor = Color.White;
//DoubleBuffered = true;
HorizontalScroll.Visible = false;
HorizontalScroll.Enabled = false;
VerticalScroll.Visible = true;
VerticalScroll.Enabled = true;
}
public void renderItemsSelected(Color color)
{
for (int q = 0; q < itemsSelected.Count; q++)
{
int i = getPos();
items[i].BackColor = color;
}
}
}
所以我想知道是否有人有任何想法?
请参阅我的回答:
WinForms - Form.DoubleBuffered 属性是否影响放置在该窗体上的控件?
基本上,在父控件上设置 DoubleBuffered 不会渗透到子控件。尝试我在该答案中提出的技巧,看看它是否适合您。
我也有类似的问题。我用以下方法解决了。
using System.Runtime.InteropServices;
internal static class NativeWinAPI
{
internal static readonly int GWL_EXSTYLE = -20;
internal static readonly int WS_EX_COMPOSITED = 0x02000000;
[DllImport("user32")]
internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32")]
internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
}
然后在主窗体中使用如下:
public MyForm()
{
InitializeComponent();
int style = NativeWinAPI.GetWindowLong(this.Handle, NativeWinAPI.GWL_EXSTYLE);
style |= NativeWinAPI.WS_EX_COMPOSITED;
NativeWinAPI.SetWindowLong(this.Handle, NativeWinAPI.GWL_EXSTYLE, style);
}