I have a handle on another process\' main window in .net (proc.MainWindowHandle). How do I maximize the window inside of .net?
I had some problems with this and finally managed to solve it. In my case I had a WinForm application that needed to maximize or minimize a WPF application.
Firstly, we need to import InteropServices
using System.Runtime.InteropServices;
Then we need methods for the actions that we require:
[DllImport("user32.dll")]
private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
Next, we can check the process by its name, get its window placement, and then update its window placement:
///
/// WINDOWPLACEMENT showCmd - 1 for normal, 2 for minimized, 3 for maximized, 0 for hide
///
public static void MaximizeProcessWindow(string processName)
{
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.Equals(processName))
{
try
{
WINDOWPLACEMENT wp = new WINDOWPLACEMENT();
GetWindowPlacement(proc.MainWindowHandle, ref wp);
// Maximize window if it is in a normal state
// You can also do the reverse by simply checking and setting
// the value of wp.showCmd
if (wp.showCmd == 1)
{
wp.showCmd = 3;
}
SetWindowPlacement(proc.MainWindowHandle, ref wp);
break;
}
catch(Exception ex)
{
// log exception here and do something
}
}
}
}
You may also get the process by the window title:
if (proc.MainWindowTitle.Equals(processTitle))
Depending on the process, your application may need to be executed under administrator privileges. This can be done by adding a manifest file and then adding the following administrator privilege: