步骤-C#GetForegroundWindow()为多个窗口返回相同的结果,EnumWindows根本不会真正返回该结

本文关键字:返回 EnumWindows 结果 -C#GetForegroundWindow 窗口 步骤 | 更新日期: 2023-09-27 18:01:10

C#的GetForegroundWindow()为多个窗口返回相同的结果,EnumWindows根本不会真正返回该窗口。每个流程都有自己的层次。

我还浏览了两个GetWindowThreadProcessId()函数,并用GetChildWindows()对它们进行了枚举,但它们仍然没有返回与GetForegroundWindow()相同的窗口。

如何正确地从GetForegroundWindow()开始,并将其转化为从正确的EnumWindows中检索到的内容?

目标:GetForegroundWindow+正确枚举以检索正确的顶级句柄(chrome中的所有选项卡,您的项目表单(,但不必筛选GetAllWindows()给您带来的混乱。谢谢

private ArrayList GetAllWindows()
{
    var windowHandles = new ArrayList();
    EnumedWindow callBackPtr = GetWindowHandle;
    EnumWindows(callBackPtr, windowHandles);
    foreach (IntPtr windowHandle in windowHandles.ToArray())
    {
        EnumChildWindows(windowHandle, callBackPtr, windowHandles);
    }
    return windowHandles;
}
private delegate bool EnumedWindow(IntPtr handleWindow, ArrayList handles);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumWindows(EnumedWindow lpEnumFunc, ArrayList lParam);
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumChildWindows(IntPtr window, EnumedWindow callback, ArrayList lParam);
List<IntPtr> ids = new List<IntPtr>();
private bool GetWindowHandle(IntPtr windowHandle, ArrayList windowHandles)
{
    windowHandles.Add(windowHandle);
    listBox1.Items.Add(windowHandle);
    //ids.Add(GetWindowThreadProcessId(windowHandle, IntPtr.Zero));
    return true;
}

步骤-C#GetForegroundWindow()为多个窗口返回相同的结果,EnumWindows根本不会真正返回该结

以下是我在Windows中使用C++的方法:

TCHAR buf[255];    
HWND foregroundWindow = GetForegroundWindow();
DWORD* processID = new DWORD;
GetWindowText(foregroundWindow, buf, 255);
GetWindowThreadProcessId(foregroundWindow, processID);
DWORD p = *processID;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
                              PROCESS_VM_READ,
                              FALSE, p);
TCHAR szProcessName[MAX_PATH];
if (NULL != hProcess )
{
    HMODULE hMod;
    DWORD cbNeeded;
    if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
                             &cbNeeded) )
    {
        GetModuleBaseName( hProcess, hMod, szProcessName,
                           sizeof(szProcessName)/sizeof(TCHAR) );
    }
}
CloseHandle(hProcess);
long pid = (long)p;

我知道你的应用程序是C#,但你也许可以使用这些Windowsneneneba API调用来获得你需要的信息。如果我能做些什么来进一步解释代码,请告诉我。