gpt4 book ai didi

C#如何判断hwnd是否在托盘图标中

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:05 25 4
gpt4 key购买 nike

我正在尝试获取当前托盘图标的 hwnd。我所做的是使用以下代码获取系统 trat 窗口的 hWnd:

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hWndParent, IntPtr hWndChildAfter, string lpClassName, string lpWindowName);


[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);


static IntPtr GetSystemTrayHandle()
{
IntPtr hWndTray = FindWindow("Shell_TrayWnd", null);
if (hWndTray != IntPtr.Zero)
{
hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, "TrayNotifyWnd", null);
if (hWndTray != IntPtr.Zero)
{
hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, "SysPager", null);
if (hWndTray != IntPtr.Zero)
{
hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, "ToolbarWindow32", null);
return hWndTray;
}
}
}

return IntPtr.Zero;
}

我从这里拿的:Finding which applications and services are listed in the System Tray?

然后我使用以下代码枚举了该 hWnd 的子窗口:

[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);

public static List<IntPtr> GetChildWindows(IntPtr parent)
{
List<IntPtr> result = new List<IntPtr>();
GCHandle listHandle = GCHandle.Alloc(result);
try
{
EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
}
finally
{
if (listHandle.IsAllocated)
listHandle.Free();
}
return result;
}

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);
// You can modify this to check to see if you want to cancel the operation, then return a null here
return true;
}

public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);

我从这里拿的:enumchildwindows (user32)

然后我这样使用它:

IntPtr temp = GetSystemTrayHandle();
List<IntPtr> tst = GetChildWindows(temp);
MessageBox.Show(tst.Count.ToString());
foreach (IntPtr ip in tst)
{
MessageBox.Show(ip.ToString());
}

但是List<IntPtr> tst是空的..知道为什么吗?我做错了吗?

最佳答案

ToolbarWindow32 的“子项”不是窗口。它们是工具栏按钮。您将使用 TB_BUTTONCOUNT 消息检索按钮的数量,使用 TB_GETBUTTONINFO 消息检索有关此类按钮的信息。顺便说一句,这很难做到,因为窗口属于另一个进程,仅使用 SendMessage() 是行不通的,因为指针无效。最终是徒劳的,这样的按钮不包含任何关于与图标相关联的进程类型的信息。这是隐藏在 shell 中的信息,您无法获取它。

关于C#如何判断hwnd是否在托盘图标中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5174120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com