经过艰苦的研究,我发现了它。问题是当你打电话时
SetWindowTheme(this.Handle, "", "");
在自定义ListView
类中,它可以防止视觉样式影响ListView
控件的外观,但不会影响ListView
标题控件(SysHeader32
窗口),它是ListView
. 所以在调用SetWindowTheme
函数的时候,我们需要提供头部窗口的句柄,而不是ListView的句柄:
[DllImportAttribute("uxtheme.dll")]
private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);
// Callback method to be used when enumerating windows:
private static bool EnumWindow(IntPtr handle, IntPtr pointer)
{
GCHandle gch = GCHandle.FromIntPtr(pointer);
List<IntPtr> list = gch.Target as List<IntPtr>;
if (list == null)
throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
list.Add(handle);
return true;
}
// delegate for the EnumChildWindows method:
private delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);
// get first child:
private static void DisableVisualStylesForFirstChild(IntPtr parent)
{
List<IntPtr> children = new List<IntPtr>();
GCHandle listHandle = GCHandle.Alloc(children);
try
{
EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
if (children.Count > 0)
SetWindowTheme(children[0], "", "");
}
finally
{
if (listHandle.IsAllocated)
listHandle.Free();
}
}
protected override void OnHandleCreated(EventArgs e)
{
DisableVisualStylesForFirstChild(this.Handle);
base.OnHandleCreated(e);
}