IntPtr taskbarWnd = WinApi.FindWindow("Shell_TrayWnd", null); IntPtr trayWnd =…
- User
IntPtr taskbarWnd = WinApi.FindWindow("Shell_TrayWnd", null); IntPtr trayWnd = WinApi.FindWindowEx(taskbarWnd, IntPtr.Zero, "TrayNotifyWnd", null); IntPtr reBarWnd = WinApi.FindWindowEx(trayWnd, IntPtr.Zero, "ReBarWindow32", null); 第三句代码返回空指针为什么
- Assistant
第三句代码可能返回空指针是因为当前系统版本的任务栏没有 "ReBarWindow32" 控件。这种情况经常出现在较旧的 Windows 操作系统或使用自定义任务栏的情况下。如果需要在不同的 Windows 版本上运行该代码,需要根据操作系统版本和任务栏类型进行适当的修改。
- User
- Assistant
- User
LPRECT、ABEdge、APPBARDATA、GetClassName、EnumChildWindows、EnumWindowsProc、SHAppBarMessage 应该怎么声明
- Assistant
LPRECT:
code[StructLayout(LayoutKind.Sequential)] public struct RECT { public int left; public int top; public int right; public int bottom; } public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct APPBARDATA { public int cbSize; public IntPtr hWnd; public uint uCallbackMessage; public uint uEdge; public RECT rc; public int lParam; } public enum ABEdge : int { ABE_LEFT = 0, ABE_TOP = 1, ABE_RIGHT = 2, ABE_BOTTOM = 3, } [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern bool EnumChildWindows(IntPtr hWndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); public delegate bool FindWindowDelegate(IntPtr hWnd, IntPtr lParam); [DllImport("shell32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SHAppBarMessage(ABMsg dwMessage, [In] ref APPBARDATA pData); public enum ABMsg : int { ABM_GETTASKBARPOS = 5, } - User
WinApi.EnumChildWindows(hShellTrayWnd, new WinApi.EnumWindowsProc(FindTrayWnd), (IntPtr)(&lprect));这一句中的&lprect出错
- Assistant
在 C# 中,不能将指向托管类型的指针隐式转换为 IntPtr 类型,因此需要显式将 RECT 结构体转换为 IntPtr 类型。
可以使用 GCHandle 来分配一个引用类型对象,然后通过 GCHandle.AddrOfPinnedObject 方法获取指向该对象的指针,再将该指针转换为 IntPtr 类型。
修改后的代码如下:
codeRECT rect = new RECT(); rect.left = lprect.left; rect.top = lprect.top; rect.right = lprect.right; rect.bottom = lprect.bottom; GCHandle gcHandle = GCHandle.Alloc(rect, GCHandleType.Pinned); IntPtr ptr = gcHandle.AddrOfPinnedObject(); WinApi.EnumChildWindows(hShellTrayWnd, new WinApi.EnumWindowsProc(FindTrayWnd), ptr); gcHandle.Free(); lprect.left = rect.left; lprect.top = rect.top; lprect.right = rect.right; lprect.bottom = rect.bottom;其中,RECT 结构体的字段 left、top、right、bottom 被赋值给了 rect 对象的相应字段,然后通过 GCHandle 分配了一个指向 rect 对象的 GCHandle,最后通过 GCHandle.AddrOfPinnedObject 方法获取了指向 rect 对象的指针。
最后需要将得到的 RECT 结构体返回给 lprect,以便在调用 GetTrayWndRect 函数的地方使用。