Maximize window of another running program

心不动则不痛 提交于 2019-12-07 13:15:35

问题


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.


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/38425378/maximize-window-of-another-running-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!