【Wince-禁止重複啓動程序】Wince 不重複啓動程序

建立類Mutex.cs:spa

using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace Demo
{
    public class Mutex
    {
        [DllImport("coredll.dll", EntryPoint = "CreateMutex", SetLastError = true)]
        public static extern IntPtr CreateMutex(
        IntPtr lpMutexAttributes,
        bool InitialOwner,
        string MutexName);

        [DllImport("coredll.dll", EntryPoint = "ReleaseMutex", SetLastError = true)]
        public static extern bool ReleaseMutex(IntPtr hMutex);

        private const int ERROR_ALREADY_EXISTS = 0183;

        /// <summary>
        /// 判斷程序是否已經運行
        /// </summary>
        /// <returns>
        /// true: 程序已運行
        /// false: 程序未運行
        /// </returns>
        public static bool IsExist()
        {
            string strAppName =
            System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            IntPtr hMutex = CreateMutex(IntPtr.Zero, true, strAppName);
            if (hMutex == IntPtr.Zero)
                throw new ApplicationException("Failure creating mutex: "
                + Marshal.GetLastWin32Error().ToString("X"));

            if (Marshal.GetLastWin32Error() == ERROR_ALREADY_EXISTS)
            {
                ReleaseMutex(hMutex);
                return true;
            }
            return false;
        }
    }
}

Programs.cs啓動:code

using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;

namespace Demo
{
    static class Program
    {

        /// <summary>
        /// 應用程序的主入口點。
        /// </summary>
        [MTAThread]
        static void Main()
        {
            if (Mutex.IsExist())
            {
                MessageBox.Show("紙頭管理程序已經啓動.");
            }
            else
            {
                try
                {

                    System.Windows.Forms.Application.Run(new FrmMain());
                }
                finally
                {
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                }

            }

        }
    }
}
相關文章
相關標籤/搜索