Reputation: 812
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.
Upvotes: 4
Views: 6235
Reputation: 3439
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);
}
Upvotes: 0
Reputation: 63299
If you make your WinForms application a singleton, then it is very easy to make the minimized window restore,
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;
}
Upvotes: 1