2011-08-24 167 views

回答

13
[DllImport("user32.dll")] 
private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow); 

static void Main() 
{ 
    Process currentProcess = Process.GetCurrentProcess(); 
    var runningProcess = (from process in Process.GetProcesses() 
          where 
          process.Id != currentProcess.Id && 
          process.ProcessName.Equals(
           currentProcess.ProcessName, 
           StringComparison.Ordinal) 
          select process).FirstOrDefault(); 
    if (runningProcess != null) 
    { 
     ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED); 
     return; 
    } 
} 

方法2

static void Main() 
{ 
    string procName = Process.GetCurrentProcess().ProcessName; 

    // get the list of all processes by the "procName"  
    Process[] processes=Process.GetProcessesByName(procName); 

    if (processes.Length > 1) 
    { 
     MessageBox.Show(procName + " already running"); 
     return; 
    } 
    else 
    { 
     // Application.Run(...); 
    } 
} 
+1

感谢重播,但对我来说还不清楚。我不知道在哪里使用这段代码。在主窗口或在app.xaml?如果登录对话框结果为true,则主窗口将打开。我甚至不知道如何显示,最大化打开的应用程序 –

+1

此代码应该转到主要方法。在这里看看有关主要方法的更多信息。 http://joyfulwpf.blogspot.com/2009/05/where-is-main-method-in-my-wpf.html – CharithJ

-1

做到这一点:

using System.Threading; 
    protected override void OnStartup(StartupEventArgs e) 
    { 
     bool result; 
     Mutex oMutex = new Mutex(true, "Global\\" + "YourAppName", 
      out result); 
     if (!result) 
     { 
      MessageBox.Show("Already running.", "Startup Warning"); 
      Application.Current.Shutdown(); 
     } 
     base.OnStartup(e); 
    } 
+0

这不会显示现有实例的窗口 –

+0

试试这个,我测试了它。 – saber

+1

我刚测试过它。第一次运行应用程序时,表单通常显示。第二次,你会看到一个对话框“已经运行”,并且当你忽略该对话时什么也没有发生。 OP希望在这种情况下显示应用程序的原始实例。使用你的解决方案,如果我最小化原始实例,或者将记事本放在它的前面,它不会被带到前台。 –

2
public partial class App 
    { 
     private const string Guid = "250C5597-BA73-40DF-B2CF-DD644F044834"; 
     static readonly Mutex Mutex = new Mutex(true, "{" + Guid + "}"); 

     public App() 
     { 

      if (!Mutex.WaitOne(TimeSpan.Zero, true)) 
      { 
       //already an instance running 
       Application.Current.Shutdown(); 
      } 
      else 
      { 
       //no instance running 
      } 
     } 
    } 
+0

对我的.NET 4.0 WPF应用程序不起作用? – Darren

1

下面是一行代码,它会为你做这个...

if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1) 
{ 
// Show your error message 
} 
相关问题