c# - 最大化另一个正在运行的程序的窗口

标签 c# .net winforms .net-4.0

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

在我的代码中我尝试过:

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

不幸的是,它只显示我的应用程序。我希望它最大化另一个 exe,但如果它找不到它,那么我想让它退出。

最佳答案

使用显示窗口

您可以使用 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);
    }
}

使用 WindowPattern.SetWindowVisualState

还有另一种选择(基于 Hans 的评论),您可以使用 SetWindowVisualState设置窗口状态的方法。为此,首先添加对 UIAutomationClient.dllUIAutomationTypes.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);
    }
}

关于c# - 最大化另一个正在运行的程序的窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38425378/

相关文章:

c# - 自定义 Silverlight 启动画面导致白屏死机

c# - 如何制作 IsNull() 方法

c# - 如何处理大于 double 最大值的浮点值

.net - 在同一个azure web应用程序上创建虚拟目录

C# WinForms 标签将显示,但不显示文本

c# - 设置调度程序以优先队列工作

c# - 来自 DataTable 的 ReportViewer 报告

c# - 将事件/命令与 XamlReader 一起使用

c# - WinForms SQLite 数据库升级技巧

c# - Web 浏览器控件的进度条