[C#] 如何讓視窗程式只有一個執行

  • 2625
  • 0
  • 2012-04-09

摘要:[C#] 如何讓視窗程式只有一個執行

C#寫視窗程式介面非常簡單

簡單到我覺得比VB還簡單

不過有些技術還蠻難找到的

譬如像是如何讓視窗程式同一時間只能有一個運行

用到的技術有

  1. DllImport呼叫C語言Win32的API
  2. 搜尋目前執行的Process中有沒有相同名稱的Process
  3. Win32視窗的Show
  4. Win32視窗的Foreground

以下程式碼是之前從Google找到的再重新修改

直接複製就可以用了(當然該改名稱的地方要自己改)

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Diagnostics;               // Process
using System.Reflection;                // Assembly
using System.Runtime.InteropServices;   // DllImport

namespace ParserTool
{
    static class Program
    {
        // cmdShow 1->normal  
        //         2->minimized
        //         3->maximized
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        /// <summary>
        /// 應用程式的主要進入點。如何讓程式單一執行
        /// </summary>
        [STAThread]
        static void Main()
        {
            /*
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new ParserTool());//*/
            Process instance = RunningInstance();
            if (instance == null)
            {
                // New an application
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new ParserTool());
            }
            else
            {
                // Make old one foreground
                ShowWindowAsync(instance.MainWindowHandle, 1);
                SetForegroundWindow(instance.MainWindowHandle);
            }
        }

        private static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        }
    }
}