简体   繁体   中英

Restore application from system tray when clicking on desktop shortcut

I've created an application that starts off in the system tray when it is started. I used the below post to achieve this: How to start WinForm app minimized to tray?

This application also only allows a single instance to run: http://www.codeproject.com/Articles/32908/C-Single-Instance-App-With-the-Ability-To-Restore

The problem I'm getting is when I first start the application it minmizes to the system tray, but if I click the desktop icon it does not appear. I have to click on the icon in the tray to restore the application. If I then minimize it again and then click on the desktop icon it appears.

This is my second attempt at a winform application, is it something to do with the SetVisibleCore?

Any pointers in the right direction would be great.

If you make your WinForms application a singleton, then it is very easy to make the minimized window restore,

http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx

It is just another variant of using WindowsFormsApplicationBase from Microsoft.VisualBasic.ApplicationServices namespace. Easier/better than using a Mutex.

You might change

    void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
    {
        Form1 form = MainForm as Form1; //My derived form type
        form.LoadFile(e.CommandLine[1]);
    }

to

    void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
    {
        Form1 form = MainForm as Form1; //My derived form type
        form.Show();
        form.WindowState = FormWindowState.Normal;
    }

What if you write the restore logic in your main. You can do this by using ShowWindow function and the SW_MAXIMIZE flag.

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

    private const int SW_MAXIMIZE = 9; //Command to restore the window

    [STAThread]
    static void Main()
    {
        bool onlyInstance = false;
        Mutex mutex = new Mutex(true, "UniqueApplicationName", out onlyInstance);
        if (!onlyInstance) 
        {
             Process[] p = Process.GetProcessesByName("UniqueApplicationName");
             SetForegroundWindow(p[0].MainWindowHandle);
             ShowWindow(p[0].MainWindowHandle, SW_MAXIMIZE);
             return;
        }
        Application.Run(new MainForm);
        GC.KeepAlive(mutex);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM