Maximize an external window using Win32 API

Hello,

I use the following code to bring an external window to the foreground, making it active:

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SetForegroundWindow (int hwnd);

   SetForegroundWindow(System.Diagnostics.Process.GetProcessById(pId).MainWindowHandle.ToInt32());

This works fine unless the window is minimized. In that case, the taskbar button gets the focus but the window does not restore to normal or maximized.

I tried the ShowWindow(pId, SW_MAXIMIZE) and that does not work. Nor does ShowWindowLong as follow:
   int      windowStyle;
   windowStyle      = GetWindowLong(process.MainWindowHandle.ToInt32(), GWL_STYLE);
   windowStyle      = windowStyle ^ WS_MAXIMIZE; // Tried with OR(|) as well as XOR(^)
   SetWindowLong(process.MainWindowHandle.ToInt32(), GWL_STYLE, windowStyle);

Any ideas?

Thanks,

Khan
raheelasadkhanAsked:
Who is Participating?
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Shoulda compiled first...

        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);
       
        [DllImport("user32.dll")]
        private static extern int ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern int SetForegroundWindow (IntPtr hWnd);

        private const int SW_RESTORE = 9;

        private void ShowPID(int pId)
        {
            IntPtr hWnd = System.Diagnostics.Process.GetProcessById(pId).MainWindowHandle;
            if (!hWnd.Equals(IntPtr.Zero))
            {
                if (IsIconic(hWnd))
                {
                    ShowWindow(hWnd, SW_RESTORE);
                }
                SetForegroundWindow(hWnd);
            }
        }
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Try something like...

        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);
       
        [DllImport("user32.dll")]
        private static extern int ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern int SetForegroundWindow (int hwnd);

        private const int SW_RESTORE = 9;

        private void ShowPID(int pId)
        {
            IntPtr hWnd = System.Diagnostics.Process.GetProcessById(pId).MainWindowHandle();
            if (!hWnd.Equals(IntPtr.Zero))
            {
                if (IsIconic(hWnd))
                {
                    ShowWindow(hWnd, SW_RESTORE);
                }
                SetForegroundWindow(hWnd);
            }
        }
0
 
raheelasadkhanAuthor Commented:
Works like a charm. Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.