【问题标题】:Minimized WinForms app restoring to Normal on second launch最小化 WinForms 应用程序在第二次启动时恢复正常
【发布时间】:2013-03-20 15:47:30
【问题描述】:

首先,我想解释一下“第二次启动”:我使用SingleInstanceController approach 可以调用我的应用程序的EXE 文件,并接受参数。

这样其他应用程序或用户可以告诉应用程序执行特定操作。

应用设置为以WindowStateMinimized 开头,并且只有当用户单击托盘图标时,它才会恢复为Normal

但我看到的是,我第一次启动应用程序时它保持最小化。然后当我第二次调用EXE文件时,它恢复到正常的窗口状态。

我没有改变窗口状态的代码。

我怀疑这是因为其他原因触发了恢复。

我的SingleInstanceController 的代码是这样的:

public class SingleInstanceController : WindowsFormsApplicationBase
{
    public SingleInstanceController()
    {
        IsSingleInstance = true;

        StartupNextInstance += this_StartupNextInstance;
    }

    void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
    {
        Form1 form = MainForm as Form1;
        string command = e.CommandLine[1];

        switch (command.ToLowerInvariant())
        {
            case "makecall":
                string phoneNumber = e.CommandLine[2];
                PhoneAppHelper.MakePhoneCall(phoneNumber);
                break;
            default:
                System.Windows.Forms.MessageBox.Show("Argument not supported");
                break;
        }
    }

    protected override void OnCreateMainForm()
    {
        MainForm = new Form1();
    }
}

在我的表单上,我有一个显示已连接设备 (USB) 的列表框和一个显示一些活动的多行文本框,主要用于调试/信息目的。

与表单上的控件的交互会导致还原吗?

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    是的,这是 WindowsFormsApplicationBase.OnStartupNextInstance() 的默认行为。您可以通过覆盖方法而不是使用事件来简单地解决这个问题。请注意,当您有要显示的消息时,您可能仍然希望发生这种情况。所以让它看起来像这样:

    protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e) {
        //...
        switch (command.ToLowerInvariant()) {
            // etc..
            default:
                base.OnStartupNextInstance(e);   // Brings it to the front
                System.Windows.Forms.MessageBox.Show("Argument not supported");
                break;
        }
    }
    

    【讨论】:

    • 太棒了!之前奇怪的是,只有第二次启动恢复了窗口状态。手动最小化窗口后,第 3 次、第 4 次...第 n 次启动保持窗口最小化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 2013-12-31
    • 1970-01-01
    相关资源
    最近更新 更多