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; 
            } 
        }
    
  • 相关阅读:
    leetcode44:wildcard
    Python实现决策树
    PCA实现
    js触摸事件
    js中的getBoundingClientRect()函数
    Java中timer的schedule()和schedualAtFixedRate()函数的区别
    nodejs中的exports和module.exports
    为什么MySQL数据库要用B+树存储索引
    浅谈微服务中的熔断,限流,降级
    缓存击穿、缓存穿透和缓存雪崩
  • 原文地址:https://www.cnblogs.com/lusunqing/p/3191359.html
Copyright © 2011-2022 走看看