I am working on WinForms. Now I want to implement one thing: when I will click on the desktop application's shortcut, and then the application is in a minimized state, then it will open from system tray (not create a new instance).
1 Answers
Okay so when you double-click the shortcut, that will actually open another instance of the application, which has no knowledge of the one already running minimised to the tray.
Essentially you want to detect that another instance of your app is running on startup. If it is, tell the existing instance of your app to show it's UI to the user, then quit.
Your solution consists of two things:
- The ability for your app to understand that another instance of it is already running.
- The ability for your app to "talk" (inter-process communication) to other instances of it and tell them what to do.
1. The ability for your app to understand that another instance of it is already running.
This is simple in .NET. When you app opens, use the Mutex
class. This is a system-wide lock, otherwise similar in nature to Monitor
.
Example:
// At app startup:
bool createdNew;
var mutex = new Mutex(true, Application.ProductName, out createdNew);
if (!createdNew)
{
// Use IPC to tell the other instance of the app to show it's UI
// Return a value that signals for the app to quit
}
// At app shutdown (unless closing because we're not the first instance):
mutex.ReleaseMutex();
2. Inter-process communication
There are a few methods for doing IPC in .NET. WCF is one, though quite heavy. Named pipes is probably the best choice for you, although it's such a simple requirement that basic socket messaging should also work.
Here's a link to a question on appropriate IPC methods in .NET to help you out: What is the best choice for .NET inter-process communication?

- 1
- 1

- 41,080
- 29
- 148
- 220
-
You don't *have* to communicate between the processes, just find the right process and activate the window.. – stuartd Mar 07 '12 at 12:56
-
Ah right okay. So I know you can iterate the processes, but how would you activate the window? – Neil Barnwell Mar 07 '12 at 15:07
-
Thanks Neil for this valuable information.This information become seed for my application :-) – Sunny Mar 08 '12 at 16:54
-
You're very welcome, but please take a quick look at the conversation between Stuart and I in the comments to my answer - looks like he has a much simpler solution that might work for you assuming the window you want to show is the application's main window. I may update my answer to include his, if he doesn't post an answer of his own in addition to the comment. – Neil Barnwell Mar 08 '12 at 16:58
-
Thanks Neil for this but i got the answer after searching.By your information i came to know about mutex class which is new for me and after that i got the working application which cover my requirement.If possible then i will provide here the solution – Sunny Mar 09 '12 at 07:23