How to execute an event of already launched application with file association?

為{幸葍}努か 提交于 2019-12-04 11:44:53
Conrad Frix

Raymond is right of course, but if you're looking for help with the implmentation of option (1) you should probably look at What is the correct way to create a single instance application? and .NET 4 single application instance and Switch to other instance of same application

You'll notice that detecting the application is pretty easy (use a mutex). Bringing the other application and sending it a filename can be more challenging.

There are three basic solutions presented in the answers to the previously linked questions

  1. Use PostMessage to send a message to 1st instance. This uses HWND_BROADCAST which can have untended consequences.

  2. Use Microsoft.VisualBasic.ApplicationServices.ApplicationBase Of course a reference to VisualBasic gives some C# devs the willies.

  3. Use FindWindow which relies on a Windows Name.

Its also worth noting that if you want the existing application to be in the front you'll need to take special care because setting the foreground can only be given away not taken. See Foreground activation permission is like love: You can't steal it, it has to be given to you and AllowSetForegroundWindow and SetForegroundWindow

There are a variety of options, but none of them come for free.

  1. Your program's Main() can detect that there is another copy already running and hand the file name off to the already-running copy by some means you determine.
  2. Your program can register as a DDE server and request that subsequent opens be performed via DDE. This is an old-fashioned technique from the 1990's that is generally not recommended for new programs.
  3. You can register a custom drop target for your application, and have the drop target hand the file name to the already-running copy. This mechanism takes the form of a shell extension, and therefore is not suitable for C# due to CLR injection issues.

Given your constraints, option (1) appears to be the best option.

Microsoft created this functionality for Visual Basic .Net, and it can be used by C# too.

See the following post for a simple example in C#:

http://www.openwinforms.com/single_instance_application.html

This approach worked best for me: Enforcing Single Instance WPF Applications. Especially, its solution for passing arguments also works in notify-icon only applications.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!