Dot-Net

如何讓 Windows 原生查找 .NET TreeView?

  • February 27, 2011

樹木

在 .NET 中使用 TreeView 組件時,我得到了左側樹的外觀。如何獲得 .NET TreeView 的正確樹的外觀(Windows Native Look)?

我特別想得到的是“三角形”節點句柄和藍色“氣泡”選擇方塊。

您需要 P/Invoke 呼叫SetWindowTheme傳遞樹的視窗句柄並使用“資源管理器”作為主題。

將以下程式碼粘貼到項目中的新類中,編譯並使用此自定義控制項而不是內置TreeView控制項。

C#:

public class NativeTreeView : System.Windows.Forms.TreeView
{
   [DllImport("uxtheme.dll", CharSet = CharSet.Unicode)]
   private extern static int SetWindowTheme(IntPtr hWnd, string pszSubAppName,
                                           string pszSubIdList);

   protected override void CreateHandle()
   {
       base.CreateHandle();
       SetWindowTheme(this.Handle, "explorer", null);
   }
}

VB.NET:

Public Class NativeTreeView : Inherits TreeView

   Private Declare Unicode Function SetWindowTheme Lib "uxtheme.dll"
       (hWnd As IntPtr, pszSubAppName As String, pszSubIdList As String) As Integer

   Protected Overrides Sub CreateHandle()
       MyBase.CreateHandle()
       SetWindowTheme(Me.Handle, "Explorer", Nothing)
   End Sub

End Class

ListView請注意,此技巧對控制項的工作方式也完全相同。

引用自:https://stackoverflow.com/questions/5131534