How to Get Active Process Name in C#?

后端 未结 5 590
失恋的感觉
失恋的感觉 2020-12-01 06:43

How to get active process name in C#?

I know that I must use this code:

[DllImport(\"user32.dll\")]
private static extern IntPtr GetForegroundWindow(         


        
5条回答
  •  离开以前
    2020-12-01 07:30

    Here's a link describing the exact thing you want to do:

    http://www.blackwasp.co.uk/GetActiveProcess.aspx

    And another one describing the GetForegroundWindow function, which I copy below.

    Note that you may need to reference some extra assemblies, for this code to work. Look at the MSDN for each function. Example, GetProcessesByName requires System.Diagnostics.

    public ApplicationState AppState
    {
        get
        {
            Process[] processCollection =
                               Process.GetProcessesByName(ProcessName);
            if(processCollection != null && 
               processCollection.Length  >= 1 && 
                processCollection[0] != null)
            {
                IntPtr activeWindowHandle = Win32.GetForegroundWindow();
                // Optional int ProcessID;
                // Optional Win32.GetWindowThreadProcessId(
                                                     GetForegroundWindow(), 
                                                     out ProcessID)
                foreach(Process wordProcess in processCollection)
                {
                    //Optional if( ProcessID == wordProcess.Id )
                    //          return ApplicationState.Focused;
                    if(wordProcess.MainWindowHandle == activeWindowHandle)
                    {
                        return ApplicationState.Focused;
                    }
                }
    
                return ApplicationState.Running;
            }
    
            return ApplicationState.NotRunning;
        }
    } 
    

提交回复
热议问题