进程主窗口标题不显示所有正在运行的进程

本文关键字:进程 运行 窗口标题 显示 | 更新日期: 2023-09-27 18:31:43

我正在开发一个扫描我的活动进程的应用程序,并在选择后将键盘命令传递给该进程。我遇到的问题是,并非所有流程似乎都有MainWindowTitle。下面是我立即认识到此问题的代码截图:

Dictionary<int, string> procInfo = new Dictionary<int, string>();
Process[] processes = Process.GetProcesses();
foreach (Process procData in processes)
{
    if (procData.MainWindowTitle.Length > 0)// || procData.ProcessName == "notepad++")
    {
        procInfo.Add(procData.Id, procData.ProcessName);
    }
}
foreach (KeyValuePair<int, string> proc in procInfo)
{
    lstProcesses.Items.Add(proc.Value + " (" + proc.Key.ToString() + ")");
}

如果您查看第 5 行,您将看到我在哪里强制 Notepad++ 进入列表以测试我来自 WinSpy++(Spy++ 的替代品)的结果,并且没有它拒绝显示的强制,因为它MainWindowTitle属性是空白的。

如果没有MainWindowTitle我无法获取应用程序的类名:

//procID set earlier and shown to be working
Process proc = Process.GetProcessById(procID);
string winTitle = proc.MainWindowTitle;
IntPtr hWnd = proc.MainWindowHandle;
StringBuilder buffer = new StringBuilder(1024);
GetClassName(hWnd, buffer, buffer.Capacity);
string winCaption = buffer.ToString();

因此,我无法将应用程序定位到传入键盘命令:

//winCaption currently blank, winTitle tested and working
IntPtr appHandler = FindWindow(winCaption, winTitle);
SetForegroundWindow(appHandler);
SendKeys.SendWait("things and junk");

我的项目有正确的DllImports设置,所以问题不存在,我在这里没有找到答案或任何可靠的互联网。我是否在代码中遗漏了一些东西,或者这只是糟糕的,我应该感觉不好吗?

进程主窗口标题不显示所有正在运行的进程

我不得不完全放弃上面的选项,转而使用 P/Invoke 解决方案:http://pinvoke.net/default.aspx/user32.EnumDesktopWindows

利用GetWindowTextGetWindowThreadProcessIDGetClassName新功能:

//the following was jacked from: http://pinvoke.net/default.aspx/user32.EnumDesktopWindows
var procCollection = new List<string>();
//Dictionary<string, int> procCollection = new Dictionary<string, int>();
EnumDelegate filter = delegate(IntPtr hWnd, int lParam)
{
    //return window titles
    StringBuilder strbTitle = new StringBuilder(255);
    int nLength = GetWindowText(hWnd, strbTitle, strbTitle.Capacity + 1);
    string winTitle = strbTitle.ToString();
    //return thread process id
    uint getID = 0;
    GetWindowThreadProcessId(hWnd, ref getID);
    int winID = Convert.ToInt32(getID);
    //return class names
    StringBuilder strbClass = new StringBuilder(255);
    GetClassName(hWnd, strbClass, strbClass.Capacity+1);
    string winClass = strbClass.ToString();
    if (IsWindowVisible(hWnd) && string.IsNullOrEmpty(winTitle) == false)
    {
        procCollection.Add(winTitle+" -- "+winID+" -- "+winClass);
    }
    return true;
};
if (EnumDesktopWindows(IntPtr.Zero, filter, IntPtr.Zero))
{
    //foreach (KeyValuePair<string, int> procInfo in procCollection)
    foreach(string procData in procCollection)
    {
        //if (procInfo.Key != "Start" && procInfo.Key != "Program Manager")
        if (procData.Contains("Start") == false && procData.Contains("Program Manager") == false)
        {
            lstProcesses.Items.Add(procData);
        }
    }
}

允许我获得构建打开的Windows列表所需的一切。这并没有给我像WinSpy++(Spy++)这样的进程列表,但它正是我所需要的。