从Main函数最大化窗口?

7

我已经使用了互斥锁来运行单个实例程序,现在如果用户重新打开应用程序时,我希望窗口变为最大化状态,即使它当前是最小化的。

这是我目前在我的Program.cs文件中拥有的代码:

static class Program
{
    [DllImport("user32.dll")]
    public static extern bool SetForegroundWindow(IntPtr hWnd);

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        bool Ok = true;
        string ProductName = Application.ProductName;
        Mutex m = new Mutex(true, ProductName, out Ok);
        if (!Ok)
        {
            System.Diagnostics.Process[] p = System.Diagnostics.Process.GetProcessesByName(ProductName);
            SetForegroundWindow(p[0].MainWindowHandle);

    }
    else
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());

    }
}

1
我可以建议恢复窗口(也就是取消最小化)比将其最大化更有意义。 - Roman Starkov
@romkyns:完全同意。正如我在答案底部提到的那样,SW_SHOW是实现这一功能的方法。这将把窗口恢复到最小化之前的状态,无论它是标准窗口还是最大化窗口。 - Cody Gray
2个回答

9
你需要查找 ShowWindow 函数SW_MAXIMIZE 标志。
在 C# 中,P/Invoke 声明如下:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

private const int SW_MAXIMIZE = 3;

在你的代码中添加它:
if (!Ok)
{
   Process[] p = Process.GetProcessesByName(ProductName);
   SetForegroundWindow(p[0].MainWindowHandle);
   ShowWindow(p[0].MainWindowHandle, SW_MAXIMIZE);
}


如果你想在最大化之前测试窗口是否被最小化,你可以使用老式的 IsIconic 函数

[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsIconic(IntPtr hWnd);

// [...]

if (!Ok)
{
   Process[] p = Process.GetProcessesByName(ProductName);
   IntPtr hwndMain= p[0].MainWindowHandle;
   SetForegroundWindow(hwndMain);

   if (IsIconic(hwndMain))
   {
      ShowWindow(hwndMain, SW_MAXIMIZE);
   }
}

如果你只想激活窗口(而不是最大化窗口),请使用SW_SHOW值(5)替代SW_MAXIMIZE。这将恢复窗口到它被最小化之前的状态。

太好了,它可以工作。只需在你的答案中修复它 [DllImport("user32.dll", CharSet = CharSet.Auto)]。 - Moslem7026
@moslem:好的,完成了。每个人都会偶尔忘记一个闭合括号。你能看出我习惯在集成开发环境中编写代码吗? - Cody Gray
SW_SHOW或值(5)对我无效 - 最小化的窗口没有任何反应(在Win XP SP3和Win 7 SP1上测试)。 SW_RESTORE或值(9)对我有效,我认为根据MSDN描述这是正确的选择。 - bairog
@bairog,没错。你必须选择正确的标志来完成你想要做的事情。SW_SHOW不能恢复或最大化一个最小化的窗口。你需要使用SW_RESTORESW_MAXIMIZE。文档是查找信息的好地方,这个答案只是为了让你开始。它是专门为原始问题而撰写的。 - Cody Gray

4

我建议使用纯 .NET 解决方案(即不依赖于操作系统)。

Program.cs

static class Program
{
    private static volatile bool _exitProcess;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        bool createdNew;
        var showMeEventHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "MyApp.ShowMe", out createdNew);

        if (createdNew)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var form = new Form1();
            new Thread(() =>
            {
                while (!_exitProcess)
                {
                    showMeEventHandle.WaitOne(-1);
                    if (!_exitProcess)
                    {
                        if (form.InvokeRequired)
                        {
                            form.BeginInvoke((MethodInvoker)form.BringFormToFront);
                        }
                        else
                        {
                            form.BringFormToFront();
                        }
                    }
                }
            }).Start();

            Application.Run(form);
        }

        _exitProcess = true;
        showMeEventHandle.Set();

        showMeEventHandle.Close();
    }
}

ExtMethods.cs

public static class ExtMethods
{
    public static void BringFormToFront(this Form form)
    {
        form.WindowState = FormWindowState.Normal;
        form.ShowInTaskbar = true;
        form.Show();
        form.Activate();
    }
}

Form1.cs

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.BringFormToFront();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            Hide();
        }
    }

1
绝对精彩,比DLL解决方案好太多了。 - Christian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接