简体   繁体   中英

Open system tray icon when click on shortcut on desktop

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).

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:

  1. The ability for your app to understand that another instance of it is already running.
  2. 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?

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