如何从App.xaml.cs调用单实例类

时间:2016-08-08 12:07:59

标签: c# wpf xaml

我有一个应用程序,只允许每个用户会话运行一个实例。如果用户再次单击以启动应用程序,我希望将该应用程序重点关注。 我按照本教程WPF Single Instance Application

中的步骤进行操作

以及本教程中的步骤是:

第1步:将文件SingleInstance.cs添加到您的项目中。

步骤2:添加对项目的引用:System.Runtime.Remoting。

步骤3:让您的应用程序类实现ISingleInstanceApp(在SingleInstance.cs中定义)。

此界面中唯一的方法是:

隐藏复制代码 bool SignalExternalCommandLineArgs(IList args) 当应用程序的第二个实例尝试运行时,将调用此方法。它有一个args参数,它与传递给第二个实例的命令行参数相同。

步骤4:定义您自己的使用单实例类的Main函数。

您的App类现在应该与此类似:

隐藏复制代码 /// 第5步:设置新的主要入口点。

选择项目属性 - >应用程序并将“启动对象”设置为您的App类名称而不是“(未设置)”。

步骤6:取消默认的WPF主功能。

右键单击App.xaml,Properties,将Build Action设置为“Page”而不是“Application Definition”。

我坚持第4步我不知道如何定义自己使用单实例类的Main函数? 请帮助我,谢谢

2 个答案:

答案 0 :(得分:0)

好的,将此方法添加到App Class的App.xaml.cs文件中非常简单:

[STAThread]    
public static void Main(string[] args)
{
    if (SingleInstance<App>.InitializeAsFirstInstance("MyApp"))
    {
        var app = new App();
        app.InitializeComponent();
        app.Run();
        // Allow single instance code to perform cleanup operations
        SingleInstance<App>.Cleanup();
    }
}

答案 1 :(得分:-1)

using System.Threading;

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

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}
相关问题