しろあじ備忘録

システム関係の備忘録。ザルのような記憶力なので、こうして書いておかないと忘れるのだよ。

【Compact Framework】c#二重起動防止 情報が少ないからメモる

Windows Embedded Compact 7  で C# のメモ。

既に古いといえる技術だし、2021年にはOSサポート終了するのだが、
必要があり、二重起動防止を組み込むことになった、、、が、
いつものノリのC#のロジックは通じないし、ネットで探してたロジックも微妙に動かなかったり、、、
もしかして、と思ったリンクを見つけたけど、Not Foundだし、、
古いってことだよなあ。。。

結局あちこちネットで見つけたコードをいくつか眺めてリファレンス見て、
以下の形で動作確認できた。


きっと私と似たような人がいるかもしれないので、残しておこう。。


using System.Runtime.InteropServices;


namespace TEST
{
    static class Program
    {
        [DllImport("coredll.dll" , SetLastError = true)]                             
        private static extern IntPtr CreateMutex(IntPtr Attr ,bool Own ,string Name) ; 

        [DllImport("coredll.dll" , SetLastError = true)]                       
        private static extern IntPtr ReleaseMutex(IntPtr hMutex ); 
        [DllImport("coredll.dll" , SetLastError = true)]                             
       private static extern IntPtr CloseHandle(IntPtr hMutex);    


  

        /// <summary>
        /// アプリケーションのメイン エントリ ポイントです。
        /// </summary>
        [MTAThread]
        static void Main(string[] args)
        {


            long ERROR_ALREADY_EXISTS  = 183; 
     
            IntPtr mutexHandle =IntPtr.Zero;
            String myName =System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;

            try
            {
               mutexHandle = CreateMutex(IntPtr.Zero, false, myName);

                if (Marshal.GetLastWin32Error() == ERROR_ALREADY_EXISTS){
                  
                    MessageBox.Show("既に起動しています");
                }else{
                    Application.Run(new frmMenu(args));
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);

            }

            ReleaseMutex(mutexHandle);
            CloseHandle(mutexHandle);
            

        }
    }
}

といっても、そう遠くない未来にリプレイスするんだろうなあ。。