Get window state of another process

前端 未结 4 1175
猫巷女王i
猫巷女王i 2020-11-30 11:46

How do I get the window state(maximized, minimized) of another process that\'s running?

I\'d tried by using this:

Process[]         


        
4条回答
  •  [愿得一人]
    2020-11-30 12:11

    You’ll need to use Win32 through P/Invoke for checking the state of another window. Here is some sample code:

    static void Main(string[] args)
    {
        Process[] procs = Process.GetProcesses();
    
        foreach (Process proc in procs)
        {
            if (proc.ProcessName == "notepad")
            {
                var placement = GetPlacement(proc.MainWindowHandle);
                MessageBox.Show(placement.showCmd.ToString());
            }
        }
    }
    
    private static WINDOWPLACEMENT GetPlacement(IntPtr hwnd)
    {
        WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
        placement.length = Marshal.SizeOf(placement);
        GetWindowPlacement(hwnd, ref placement);
        return placement;
    }
    
    [DllImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool GetWindowPlacement(
        IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
    
    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    internal struct WINDOWPLACEMENT
    {
        public int length;
        public int flags;
        public ShowWindowCommands showCmd;
        public System.Drawing.Point ptMinPosition;
        public System.Drawing.Point ptMaxPosition;
        public System.Drawing.Rectangle rcNormalPosition;
    }
    
    internal enum ShowWindowCommands : int
    {
        Hide = 0,
        Normal = 1,
        Minimized = 2,
        Maximized = 3,
    }
    

    Definition courtesy of pinvoke.net.

提交回复
热议问题