最大化另一个运行程序的窗口

Pri*_*ton 3 .net c# .net-4.0 winforms

如何以编程方式最大化我当前在我的电脑上运行的程序.例如,如果我WINWORD.exe在任务管理器中运行.我如何最大化它?

在我的代码中,我尝试过:

private void button1_Click(object sender, EventArgs e)
{
    this.WindowState = FormWindowState.Maximised;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,它只显示我的应用 我想它最大化另一个exe,但如果它找不到它然后我想它退出.

Rez*_*aei 9

使用ShowWindow

您可以使用ShowWindow方法设置窗口状态.为此,首先需要找到窗口句柄然后使用该方法.然后以这种方式最大化窗口:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用WindowPattern.SetWindowVisualState

另外作为另一种选择(基于Hans的评论),您可以使用SetWindowVisualState方法来设置窗口的状态.为此,首先添加一个引用UIAutomationClient.dll,UIAutomationTypes.dll然后using System.Windows.Automation;以这种方式添加和最大化窗口:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)