.NET 4单个应用程序实例 [英] .NET 4 single application instance

查看:222
本文介绍了.NET 4单个应用程序实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常写.NET应用程序只支持一个实例。以前我用.NET的远程处理,现在WCF来检测是否已经我的应用程序的一个实例正在运行,并给予重点此实例。

I often write .net applications that only support one instance. Formerly I used .net-remoting and now WCF to detect if already an instance of my app is running and giving the focus to this instance.

我的问题是,如果没有与.NET4一个更好的解决方案,可实现单实例应用程序(或有一般一个更好的解决方案可用,因为加载WCF或应用程序的最开始远程处理组件具有不良性能影响)

My question is, if there is with .net4 a better solution available to achieve single instance applications (or is there in general a better solution available, because loading the WCF or remoting assembly at the very start of the application has a bad performance influence)

更新

感谢所有的职位。回答我最初的问题似乎是否,有什么新的在.NET 4 实现单实例应用程序。

Thanks for all the post. The answer to my initial question seems to be "no, there is nothing new to achieve single instance applications within .net 4".

感谢所有的其他信息,我会改变我目前的项目中使用互斥来提供所需的功能。我接受了鲍勃·摩尔的答案,因为它连接到它的信息最多,但感谢所有谁张贴的有用信息。

Thanks to all the additional information, I will change my current projects to use a Mutex to provide the desired functionality. I accepted the answer of Bob Moore because it has the most information attached to it, but thanks to all who posted useful information.

推荐答案

传统的方式做,这是一个互斥体,如:

The traditional way to do this is with a mutex, e.g.

bool bNew = true; 
using (Mutex mutex = new Mutex(true, "MYAPP_0D36E4C9-399D-4b05-BDA3-EE059FB77E8D", out bNew))
{
   if (bNew)
   {
       // blah, blah,
       Application.Run(new MainForm());
   }
}

编辑:

我发现这个code网上调用SetForegroundWindow,所以你可以找到你的应用程序的其他实例,并显示它:

I found this code to invoke SetForegroundWindow online, so you can find the other instance of your app and bring it forward:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);


Process me = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName (me.ProcessName))
{
   if (process.Id != me.Id)
   {
      SetForegroundWindow (process.MainWindowHandle);
      break;
   }
}

请注意,在现代的Windows实现,你只能给前台了。

Note that in modern Windows implementations you can only give the foreground away.

这篇关于.NET 4单个应用程序实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆