I have a handle on another process' main window in .net (proc.MainWindowHandle). How do I maximize the window inside of .net?
You can pinvoke to ShowWindow with SW_SHOWMAXIMIZED to maximize the window.
Pinvoke.net has an entry for ShowWindow here.
For example,
// Pinvoke declaration for ShowWindow
private const int SW_SHOWMAXIMIZED = 3;
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
// Sample usage
ShowWindow(proc.MainWindowHandle, SW_SHOWMAXIMIZED);
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:
/// <summary>
/// WINDOWPLACEMENT showCmd - 1 for normal, 2 for minimized, 3 for maximized, 0 for hide
/// </summary>
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:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
You could also use SetWindowPlacement. There's further info about it on Pinvoke.net.
© 2022 - 2024 — McMap. All rights reserved.