WPF程序只有一个实例运行

WPF程序只运行一个实例;

下面的代码还 尝试,如果窗体最小化的时候,让窗体还原

public partial class App : Application
   {
       private static Semaphore singleInstanceWatcher;
       private static bool createdNew;

       static App()
       {
           // Ensure other instances of this application are not running.
           singleInstanceWatcher = new Semaphore(
               0, // Initial count.
               1, // Maximum count.
               Assembly.GetExecutingAssembly().GetName().Name,
               out createdNew);

           if (createdNew)
           {
               // This thread created the kernel object so no other instance
               // of this application must be running.
               //Application currApp = Application.Current;
               //currApp.StartupUri = new Uri("MainWindow.xaml", UriKind.RelativeOrAbsolute);
               MainWindow win = new MainWindow();
               win.Show();
           }
           else
           {
               // This thread opened an existing kernel object with the same
               // string name; another instance of this app must be running now.
               // Gets a new System.Diagnostics.Process component and the
               // associates it with currently active process.
               Process current = Process.GetCurrentProcess();

               // Enumerate through all the process resources on the share
               // local computer that the specified process name.
               foreach (Process process in
                    Process.GetProcessesByName(current.ProcessName))
               {
                   if (process.Id != current.Id)
                   {
                       NativeMethods.SetForegroundWindow(
                           process.MainWindowHandle);
                       NativeMethods.ShowWindow(process.MainWindowHandle,
                           WindowShowStyle.Restore);
                       break;
                   }
               }

               // Terminate this process and gives the underlying operating
               // system the specified exit code.
               Environment.Exit(-2);
           }

 // 如果代码在Application_Startup中 如下
       // private Semaphore singleInstanceWatcher;
         // private bool createdNew;

           //private void Application_Startup(object sender, StartupEventArgs e)
           //{
           //    singleInstanceWatcher = new Semaphore(
           //   0, // Initial count.
           //   1, // Maximum count.
           //   Assembly.GetExecutingAssembly().GetName().Name,
           //   out createdNew);
           //    if (createdNew)
           //    {
           //        // This thread created the kernel object so no other instance
           //        // of this application must be running.
           //        Application currApp = Application.Current;
           //        currApp.StartupUri = new Uri("MainWindow.xaml", UriKind.RelativeOrAbsolute);
           //    }
           //    else
           //    {
           //        //MessageBox.Show("系统已经运行");
           //        Process current = Process.GetCurrentProcess();
           //        foreach (Process process in
           //             Process.GetProcessesByName(current.ProcessName))
           //        {
           //            if (process.Id != current.Id)
           //            {

           //                NativeMethods.SetForegroundWindow(
           //                    process.MainWindowHandle);
           //                NativeMethods.ShowWindow(process.MainWindowHandle,
           //                    WindowShowStyle.Restore);
           //                break;
           //            }
           //        }
           //        Environment.Exit(-2);
           //    }

       }
   }
       internal enum WindowShowStyle : uint
       {
           /// <summary>Hides the window and activates another window.</summary>
           /// <remarks>See SW_HIDE</remarks>
           Hide = 0,
           /// <summary>Activates and displays a window. If the window ..
           /// or maximized, the system restores it to its original size and
           /// position. An application should specify this flag when displaying
           /// the window for the first time.</summary>
           /// <remarks>See SW_SHOWNORMAL</remarks>
           ShowNormal = 1,
           /// <summary>Activates the window and displays it ..</summary>
           /// <remarks>See SW_SHOWMINIMIZED</remarks>
           ShowMinimized = 2,
           /// <summary>Activates the window and displays it ..</summary>
           /// <remarks>See SW_SHOWMAXIMIZED</remarks>
           ShowMaximized = 3,
           /// <summary>Maximizes the specified window.</summary>
           /// <remarks>See SW_MAXIMIZE</remarks>
           Maximize = 3,
           /// <summary>Displays a window in its most recent size and position.
           /// This value is similar to "ShowNormal", except the window is not
           /// actived.</summary>
           /// <remarks>See SW_SHOWNOACTIVATE</remarks>
           ShowNormalNoActivate = 4,
           /// <summary>Activates the window and displays it in its current size
           /// and position.</summary>
           /// <remarks>See SW_SHOW</remarks>
           Show = 5,
           /// <summary>Minimizes the specified window and activates the next
           /// top-level window in the Z order.</summary>
           /// <remarks>See SW_MINIMIZE</remarks>
           Minimize = 6,
           /// <summary>Displays the window as a minimized window. This value is
           /// similar to "ShowMinimized", except the window ..</summary>
           /// <remarks>See SW_SHOWMINNOACTIVE</remarks>
           ShowMinNoActivate = 7,
           /// <summary>Displays the window in its current size and position. This
           /// value is similar to "Show", except the window ..</summary>
           /// <remarks>See SW_SHOWNA</remarks>
           ShowNoActivate = 8,
           /// <summary>Activates and displays the window. If the window is
           /// minimized or maximized, the system restores it to its original size
           /// and position. An application should specify this flag ..
           /// a minimized window.</summary>
           /// <remarks>See SW_RESTORE</remarks>
           Restore = 9,
           /// <summary>Sets the show state based on the SW_ value specified ..
           /// STARTUPINFO structure passed to the CreateProcess function by the
           /// program that started the application.</summary>
           /// <remarks>See SW_SHOWDEFAULT</remarks>
           ShowDefault = 10,
           /// <summary>Windows 2000/XP: Minimizes a window, even if the thread
           /// that owns the window is hung. This flag should only be used when
           /// minimizing windows from a different thread.</summary>
           /// <remarks>See SW_FORCEMINIMIZE</remarks>
           ForceMinimized = 11
       }
       static class NativeMethods
       {
           /// <summary>
           /// Brings the thread that created the specified window into the
           /// foreground and activates the window. Keyboard input is directed
           /// to the window, and various visual cues are changed for the user.
           /// The system assigns a slightly higher priority to the thread that
           /// created the foreground window than it does to other threads.
           /// </summary>
           /// <param name="hWnd">A handle to the window that should be
           /// activated and brought to the foreground.
           /// </param>
           /// <returns>If the window was brought to the foreground, the
           /// return value is nonzero. </returns>
           [DllImport("user32.dll")]
           internal static extern bool SetForegroundWindow(IntPtr hWnd);

           /// <summary>Shows a Window</summary>
           /// <remarks>
           /// <para>To perform certain special effects when showing or hiding a
           /// window, use AnimateWindow.</para>
           /// <para>The first time an application calls ShowWindow, it should use
           /// the WinMain function‘s nCmdShow parameter as its nCmdShow ..
           /// Subsequent calls to ShowWindow must use one of the values in the
           /// given list, instead of the one specified by the WinMain function‘s
           /// nCmdShow parameter.</para>
           /// <para>As noted in the discussion of the nCmdShow parameter, the
           /// nCmdShow value is ignored in the first call to ShowWindow if the
           /// program that launched the application specifies startup information
           /// in the structure. In this case, ShowWindow uses the information
           /// specified in the STARTUPINFO structure to show the window. On
           /// subsequent calls, the application must call ShowWindow with ..
           /// set to SW_SHOWDEFAULT to use the startup information provided by ..
           /// program that launched the application. This behavior is designed ..
           /// the following situations: </para>
           /// <list type="">
           ///    <item>Applications create their main window by calling ..
           ///    with the WS_VISIBLE flag set. </item>
           ///    <item>Applications create their main window by calling ..
           ///    with the WS_VISIBLE flag cleared, and later call ShowWindow ..
           ///    SW_SHOW flag set to make it visible.</item>
           /// </list></remarks>
           /// <param name="hWnd">Handle to the window.</param>
           /// <param name="nCmdShow">Specifies how the window is to be shown.
           /// This parameter is ignored the first time an application calls
           /// ShowWindow, if the program that launched the application provides a
           /// STARTUPINFO structure. Otherwise, the first time ShowWindow .. ,
           /// the value should be the value obtained by the WinMain function ..
           /// nCmdShow parameter. In subsequent calls, this parameter ..
           /// the WindowShowStyle members.</param>
           /// <returns>
           /// If the window was previously visible, the return value is nonzero.
           /// If the window was previously hidden, the return value is zero.
           /// </returns>
           [DllImport("user32.dll")]
           internal static extern bool ShowWindow(IntPtr hWnd,
               WindowShowStyle nCmdShow);
       }
时间: 2024-09-29 10:16:04

WPF程序只有一个实例运行的相关文章

[C#]只能运行程序的一个实例

C#实现只能运行程序的一个实例(添加在窗体的Load事件中) 1. 根据进行名限制只能运行程序的一个实例 System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess(); System.Diagnostics.Process[] processList = System.Diagnostics.Process.GetProcessesByName(process.ProcessName); 

【原创】大叔经验分享(82)logstash一个实例运行多个配置文件

logstash一个实例运行多个配置文件,将所有配置文件放到以下目录即可 /usr/share/logstash/pipeline 但是默认行为不是每个配置文件独立运行,而是作为一个整体,每个input会匹配所有的filter,然后匹配所有的output,可能会导致数据被错误的处理以及发送到错误的地方: 解决方法一: 在input中设置一个变量,在filter和output中判断该变量,实现每个配置文件独立运行,不会相互影响,使用哪个变量呢? input默认有很多通用参数,但是只有type可用,

Sqlserver Sql Agent Job 只能同时有一个实例运行

Sqlserver Sql Agent中的Job默认情况下只能有一个实例在运行,也就是说假如你的Sql Agent里面有一个正在运行的Job叫"Test Job",如果你现在再去启动一次"Test Job"就会报错,因为Sqlserver规定在一个Sqlserver账号下,Sql Agent不能同时启动相同的Job两次,只有前一次启动执行完成后,才能够再次启动该Job. 那么随之而来的问题是如何用sql语句检测Job是否已经执行完毕了呢?下面有一个语句可以作为参考:

转 C# 只允许运行一个实例

来源:http://blog.csdn.net/jin20000/article/details/3136791 互斥进程(程序), 简单点说,就是在系统中只能有该程序的一个实例运行. 现在很多软件都有这功能,如Maxthon 可以设置为"只允 许打开一个窗体",还有Bitcomet等. 我也是看到这些软件的这个功能才来研究这个问题的.  要实现程序的互斥,通常有三中方式,下面 用 C#  语言来实现: 实现方式一: 使用线程互斥变量. 通过定义互斥变量来判断是否已运行实例.C#实现如

[VC]在VC++中实现让程序只运行一个实例的方法且实现该实例

方法一: 有时候在开发应用程序时,希望控制程序运行唯一的实例.例如,最常用的mp3播放软 件Winamp,由于它需要独占计算机中的音频设备,因此该程序只允许自身运行唯一的一个例程.在Visual C++的开发实践中,对于16位的Windows系统,应用程序的hPrevInstance句柄保存了应用程序上一个运行的实例,可以用该值来检查是否 有实例运行:然而在32位Windows系统下,这个值总是NULL,所以无法利用该值来实现程序运行唯一实例.本实例给出了解决这个问题的简单办法,只 要将程序中稍

Java程序只运行一个实例[转]

如果希望你的Java程序只能存在一个实例,可以参考下面的用法. 原文链接:http://blog.csdn.net/yaerfeng/article/details/7264729 Java没有提供这样的机制.从操作系统的观点来看,一个启动的Java Application仅仅是一个JVM的运行实例.运行相同Application的两个实例,仅仅是运行两个无关的JVM.       只有让多个运行实例之间有一个既定的通讯机制就可以保证只有一个实例运行. 方案1:使用Java的加锁文件机制,ide

c#设计应用程序单实例运行

利用WindowsFormsApplicationBase的IsSingleInstance来控制应用程序只能单实例运行. [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)] public static extern int ShowWindow(IntPtr hwnd, int nCmdShow); [DllImport("User32.dll"

C#应用程序只允许运行一个实例,多次运行的时候激活当前实例,显示其界面

很多时候,我们开发的程序,需要单例运行的的功能,即整个应用程序只允许同时运行最多一个实例,重复运行的时候,激活当前实力,显示其界面. 在C#程序中,其解决方案有多重,可以参照Charles Chen 的C#程序只允许运行一个实例的解决方案一文. 参照其文章,我决定使用调用Windows Api的方法,大致如下: namespace BarCodeSystem { public static class Program { /// <summary> /// Application Entry

C# WinForm 判断程序是否已经在运行,且只允许运行一个实例

static class Program {   /// <summary>   /// 应用程序的主入口点.   /// </summary>   [STAThread]   static void Main()   {     Application.EnableVisualStyles();     Application.SetCompatibleTextRenderingDefault(false);     //1.这里判定是否已经有实例在运行     //只运行一个实