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; 
            } 
        }
    
  • 相关阅读:
    CentOS 7下PXE+Kickstart无人值守安装操作系统
    利用pentestbox打造ms17-010移动"杀器"
    XSS测试代码
    sublime Text3基本配置记录+python
    CTF中那些脑洞大开的编码和加密
    信息安全相关资源
    RIP 实验
    python输出有色记录
    下载Chrome商店和Youtube资源
    mysql使用问题记录
  • 原文地址:https://www.cnblogs.com/lusunqing/p/3191359.html
Copyright © 2011-2022 走看看