处理MainWindowTitle不显示所有正在运行的进程

时间:2014-11-24 20:22:47

标签: c# process

我正在处理一个扫描我的活动进程的应用程序,在选择之后,将关键命令传递给该进程。我遇到的问题是并非我的所有进程似乎都有MainWindowTitle。下面是代码snippit,我立即发现了这个问题:

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,所以问题不在那里,我没有在这里找到答案或任何可靠的巡航其余的互联网。我在代码中遗漏了什么,或者这只是坏事,我应该感觉不好吗?

1 个答案:

答案 0 :(得分:0)

我不得不完全取消上面的选项,转而使用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 ++)这样的进程列表,但它正是我需要的。