Windows Mobile只運行一個執行個體

來源:互聯網
上載者:User

因為一個項目的需求,要實現程式只有一個執行個體運行。在網上搜了很久,最後在CSDN上面看到一回複。得到啟示,完成該功能。

主要用的是互斥對象來實現。代碼如下:

    static class Program
    {
        [DllImport("coredll.Dll",SetLastError= true)]
        private static extern IntPtr CreateMutex(SECURITY_ATTRIBUTES lpMutexAttributes, bool bInitialOwner, string lpName);

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

        [StructLayout(LayoutKind.Sequential)]
        public class SECURITY_ATTRIBUTES
        {
            public int nLength;
            public int lpSecurityDescriptor;
            public int bInheritHandle;
        }

        const int ERROR_ALREADY_EXISTS = 0183; 

        /// <summary>
        /// 應用程式的主進入點。
        /// </summary>
        [MTAThread]
        static void Main()
        {
            IntPtr hMutex = CreateMutex(null, false, "StandardWorkMan");
            if (Marshal.GetLastWin32Error() != ERROR_ALREADY_EXISTS)
            {
                Application.Run(new FormWorkList());
            }
            else
            {
                MessageBox.Show("已經啟動了一個程式,請勿重複開啟", "系統提示",
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                ReleaseMutex(hMutex);
                Application.Exit();
            }
            
        }
    }

 

上面代碼完全正常,我的問題是大部分自己很早就寫出來了。只是問題在下面:

[DllImport("coredll.Dll",SetLastError = true)]
private static extern int GetLastError();

.

if (GetLastError() != ERROR_ALREADY_EXISTS)
{
     Application.Run(new FormWorkList());
}

 

 我用的是平台叫用裡面的GetLastError(),結果一直出不來想要的效果。調試時發現無論開啟多少個執行個體,GetLastError()的值一直都是6(INVALID_HANDLE_VALUE)????很不解。 望明白的人說明一下。謝謝。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.