How to get the active name of the application window, as shown in the task manager

I am trying to get the name of the active window as shown in the task manager application list (using C #). I had the same problem as described here . I tried to do what they described, but I have a problem, while a focused application is an image library in which I get an exception. I also tried this one , but nothing gives me the expected results. At the moment I am using:

IntPtr handle = IntPtr.Zero;
handle = GetForegroundWindow();

const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
if (GetWindowText(handle, Buff, nChars) > 0)
{
    windowText = Buff.ToString();
}

and delete something that doesn't matter based on the table I created for most regular applications, but I don’t like this workaround. Is there a way to get the name of the application, as in the task manager for the entire running application?

+4
2

: . , , ​​ , . , , , :

[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

public string GetActiveWindowTitle()
{
    var handle = GetForegroundWindow();
    string fileName = "";
    string name = "";
    uint pid = 0;
    GetWindowThreadProcessId(handle, out pid);

    Process p = Process.GetProcessById((int)pid);
    var processname = p.ProcessName;

    switch (processname)
    {
        case "explorer": //metro processes
        case "WWAHost":
            name = GetTitle(handle);
            return name;
        default:
            break;
    }
    string wmiQuery = string.Format("SELECT ProcessId, ExecutablePath FROM Win32_Process WHERE ProcessId LIKE '{0}'", pid.ToString());
    var pro = new ManagementObjectSearcher(wmiQuery).Get().Cast<ManagementObject>().FirstOrDefault();
    fileName = (string)pro["ExecutablePath"];
    // Get the file version
    FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(fileName);
    // Get the file description
    name = myFileVersionInfo.FileDescription;
    if (name == "")
        name = GetTitle(handle);

 return name;
}

public string GetTitle(IntPtr handle)
{
string windowText = "";
    const int nChars = 256;
    StringBuilder Buff = new StringBuilder(nChars);
    if (GetWindowText(handle, Buff, nChars) > 0)
    {
        windowText = Buff.ToString();
    }
    return windowText;
}
+4

, ( , EnumWindows pinvoke http://msdn.microsoft.com/en-us/library/windows/desktop/ms633497(v=vs.85).aspx) GetwindowText pinvoke.

EnumWindows will ' , , , , .

0

Source: https://habr.com/ru/post/1530264/


All Articles