淺談如何讓W(xué)indows Mobile只運(yùn)行一個實(shí)例
作者:李玉寶
本文將簡單談?wù)勅绾巫學(xué)indows Mobile只運(yùn)行一個實(shí)例,其中主要用到的互斥的概念。文末作者還提出了自己的一些問題,希望大家積極討論。
因?yàn)橐粋€項(xiàng)目的需求,要實(shí)現(xiàn)程序只有一個實(shí)例運(yùn)行。在網(wǎng)上搜了很久,最后在CSDN上面看到一回復(fù)。得到啟示,完成該功能。
主要用的是互斥對象來實(shí)現(xiàn)。代碼如下:
- staticclassProgram
- {
- [DllImport("coredll.Dll",SetLastError=true)]
- privatestaticexternIntPtrCreateMutex(SECURITY_ATTRIBUTESlpMutexAttributes,boolbInitialOwner,stringlpName);
- [DllImport("coredll.Dll",SetLastError=true)]
- privatestaticexternintReleaseMutex(IntPtrhMutex);
- [StructLayout(LayoutKind.Sequential)]
- publicclassSECURITY_ATTRIBUTES
- {
- publicintnLength;
- publicintlpSecurityDescriptor;
- publicintbInheritHandle;
- }
- constintERROR_ALREADY_EXISTS=0183;
- ///<summary>
- ///應(yīng)用程序的主入口點(diǎn)。
- ///</summary>
- [MTAThread]
- staticvoidMain()
- {
- IntPtrhMutex=CreateMutex(null,false,"StandardWorkMan");
- if(Marshal.GetLastWin32Error()!=ERROR_ALREADY_EXISTS)
- {
- Application.Run(newFormWorkList());
- }
- else
- {
- MessageBox.Show("已經(jīng)啟動了一個程序,請勿重復(fù)打開","系統(tǒng)提示",
- MessageBoxButtons.OKCancel,MessageBoxIcon.Asterisk,MessageBoxDefaultButton.Button1);
- ReleaseMutex(hMutex);
- Application.Exit();
- }
- }
- }
上面代碼完全正常,我的問題是大部分自己很早就寫出來了。只是問題在下面:
- [DllImport("coredll.Dll",SetLastError=true)]
- privatestaticexternintGetLastError();
- .
- if(GetLastError()!=ERROR_ALREADY_EXISTS)
- {
- Application.Run(newFormWorkList());
- }
我用的是平臺調(diào)用里面的GetLastError(),結(jié)果一直出不來想要的效果。調(diào)試時發(fā)現(xiàn)無論打開多少個實(shí)例,GetLastError()的值一直都是6(INVALID_HANDLE_VALUE)????很不解。望明白的人說明一下。謝謝。
【編輯推薦】
責(zé)任編輯:彭凡
來源:
cnblogs