3

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;
}
4

1 回答 1

0

这是我在 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#,但您也许可以使用其中一些 Windows API 调用来获取您需要的信息。让我知道是否可以做任何事情来进一步解释代码。

于 2013-03-28T20:13:52.133 回答