zoukankan      html  css  js  c++  java
  • 转:限制应用程序运行一次并激活已经运行的程序 .

    转载自:http://blog.csdn.net/zhxingway/article/details/5288662

    C#单实例运行实现
    在某些情况我们要求应用程序只能运行一次,后运行的实例要把之前运行的程序激活并自己退出。
    现在是代码,找了好久哦,大家给点掌声吧,呵呵 .
    关键词:winform限制主程序运行一次,激活程序,我是直接把我项目中Program.cs中的代码Copy过来了,希望大家不要见怪.

        static class Program
        {
            // Uses to active the exist window
            [DllImport("User32.dll")]
            public static extern void SetForegroundWindow(IntPtr hwnd);
            [DllImport("User32.dll")]
            private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
            // 0-Hidden, 1-Centered, 2-Minimized, 3-Maximized
            private const int WS_SHOWNORMAL = 1;
            
            /// <summary>
            /// 应用程序的主入口点。
             /// </summary>
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                //限制程序只打开一次
                  if (RunningInstance() == null)
                {
                    Application.Run(new Form1());
                }
                //Application.Run(new RecordQuery());
            }
    
            /// <summary>
            /// 限制程序只打开一次
             /// </summary>
            /// <returns></returns>
            public static Process RunningInstance() 
            { 
                Process current = Process.GetCurrentProcess(); 
                Process[] processes = Process.GetProcessesByName(current.ProcessName); 
                //Loop through the running processes in with the same name 
                foreach (Process process in processes) 
                { 
                    //Ignore the current process 
                    if (process.Id != current.Id) 
                    { 
                        //Make sure that the process is running from the exe file. 
                        if (Assembly.GetExecutingAssembly().Location.Replace("/", "//") == current.MainModule.FileName) 
                        { 
                            //Return the other process instance. 
                            ShowWindowAsync(process.MainWindowHandle, WS_SHOWNORMAL);
                            SetForegroundWindow(process.MainWindowHandle);
                            return process; 
                        } 
                    } 
                } 
                //No other instance was found, return null. 
                return null; 
            } 
        }
    
  • 相关阅读:
    winform,WPF 释放内存垃圾,减少资源占用方法
    Winform中使用WPF控件并动态读取Xaml
    Winform程序双向绑定
    STM32L15XXX 入门笔记
    STM32固件库下载地址
    C#实现虚拟控件列表显示100w个控件方法
    DotNetBar滚动条的疑似BUG
    VS Sln图标空白修复办法
    Swift下使用Xib设计界面
    关于Mac OS虚拟机下共享文件夹的方法
  • 原文地址:https://www.cnblogs.com/lusunqing/p/3191359.html
Copyright © 2011-2022 走看看