Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximize window of another running program

How do I programmatically maximize a program that I have currently running on my pc. For example if I have WINWORD.exe running in task manager. How do I maximize it?

In my code I have tried:

private void button1_Click(object sender, EventArgs e)
{
    this.WindowState = FormWindowState.Maximised;
}

Unfortunately that only displays my application. I would like it to maximise another exe, BUT if it cannot find it then i want to it to exit.

like image 994
PriceCheaperton Avatar asked Dec 10 '22 15:12

PriceCheaperton


1 Answers

Using ShowWindow

You can set windows state using ShowWindow method. To do so, you first need to find the window handle and then using the method. Then maximize the window this way:

private const int SW_MAXIMIZE = 3;
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private void button1_Click(object sender, EventArgs e)
{
    var p = System.Diagnostics.Process.GetProcessesByName("WINWORD").FirstOrDefault();
    if(p!=null)
    {
        ShowWindow(p.MainWindowHandle, SW_MAXIMIZE);
    }
}

Using WindowPattern.SetWindowVisualState

Also as another option (based on Hans's comment), you can use SetWindowVisualState method to set state of a window. To so so, first add a reference to UIAutomationClient.dll and UIAutomationTypes.dll then add using System.Windows.Automation; and maximize the window this way:

var p = System.Diagnostics.Process.GetProcessesByName("WINWORD").FirstOrDefault();
if (p != null)
{
    var element = AutomationElement.FromHandle(p.MainWindowHandle);
    if (element != null)
    {
        var pattern = element.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern;
        if (pattern != null)
            pattern.SetWindowVisualState(WindowVisualState.Maximized);
    }
}
like image 137
Reza Aghaei Avatar answered Dec 20 '22 11:12

Reza Aghaei