C# Windows CE使用小技巧實例
C# Windows CE使用的一些感受:使用Windows的開發(fā)機上用C#啟動一個外部程序的方法有很多,但這些方法用在使用WinCE的目標工控機上都無能為力。
C# Windows CE使用1、
現在以打開一個IE為例,介紹如何在WinCE下使用C#來打開一個外部文件:
首先添加命名空間
- usingSystem.Runtime.InteropServices;,
然后調用API函數:
- [DllImport("coredll.Dll",
- EntryPoint="CreateProcess",SetLastError=true)]
- externstaticintCreateProcess(
- stringstrImageName,stringstrCmdLine,
- IntPtrpProcessAttributes,IntPtrpThreadAttributes,
- intbInheritsHandle,intdwCreationFlags,
- IntPtrpEnvironment, IntPtrpCurrentDir,
- IntPtrbArray,ProcessInfooProc);
- publicclassProcessInfo
- {
- publicInt32hProcess;
- publicInt32hThread;
- publicInt32ProcessID;
- publicInt32ThreadID;
- }
最后就可以編寫需要打開IE的代碼了(點擊一個按鈕打開IE瀏覽器中相應內容,此例程要求打開目標工控機硬盤上的Readme文件):
- privatevoidbutton_Click(
- objectsender,System.EventArgse)
- {
- ProcessInfopi=newProcessInfo();
- CreateProcess(" \\windows\\iesample.exe",
- "\\HardDisk\\Readme.htm",IntPtr.Zero,
- IntPtr.Zero,0,0,IntPtr.Zero,
- IntPtr.Zero,IntPtr.Zero,pi);
- }
C# Windows CE使用2、
有時候我們會希望我們的程式只被執(zhí)行一次,VB的時代我們會用App.PrevInstance,而.net的時代我們可以用下列方式實現
- [STAThread]
- staticvoidMain()
- {
- //如果跟本程式命名的行程只有一個才執(zhí)行程式
- if(System.Diagnostics.Process.
- GetProcessesByName(
- Application.ProductName).Length==1)
- {
- Application.Run(newForm1());
- }
- }
但此方法在WinCE下無法實現,所以我們還是要先調用動態(tài)鏈接庫,
- [DllImport("coredll.Dll")]
- privatestaticexternintGetLastError();
- [DllImport("coredll.Dll")]
- privatestaticexternintReleaseMutex(IntPtrhMutex);
- [DllImport("coredll.Dll")]
- privatestaticexternIntPtrCreateMutex(
- SECURITY_ATTRIBUTESlpMutexAttributes,
- boolbInitialOwner,stringlpName);
- [StructLayout(youtKind.Sequential)]
- publicclassSECURITY_ATTRIBUTES
- {
- publicintnLength;
- publicintlpSecurityDescriptor;
- publicintbInheritHandle;
- }
- constintERROR_ALREADY_EXISTS=0183;
然后編寫代碼
- staticvoidMain()
- {
- #regionApi_CallCreateMutex;
- IntPtrhMutex;
- hMutex=CreateMutex(null,false,"程序名");
- if(GetLastError()!=ERROR_ALREADY_EXISTS)
- {
- Application.Run(newFrmmenu());
- }
- else
- {
- MessageBox.Show("本程序只允許同時運行一個");
- ReleaseMutex(hMutex);
- }
- #endregion
- }
C# Windows CE使用3、
在.NETFramework中沒有函數可以激活屬于另外一個進程或程序的窗體,所以我們要通過調用API函數來實現:
- usingSystem.Runtime.InteropServices;
- [DllImport("coredll.Dll")]
- publicstaticexternIntPtrFindWindow(
- Stringclassname,Stringtitle);
- [DllImport("coredll.Dll")]
- publicstaticexternvoidSetForegroundWindow(IntPtrhwnd);
然后使用下列代碼即可
- IntPtrhDlg;
- hDlg=FindWindow(null,"窗口標題");
- SetForegroundWindow(hDlg);
最后,WinCE下的C#里不支持GroupBox控件,建議使用Panel控件代替;不支持Frame控件,如果非要達到那樣的效果,可以用Label和TextBox組和起來應付一下。
其實,任何時候,只要.NETFramework無法滿足編程者需要的時候,通常都可以使用托管(interop)機制直接與Windows交互。大家也許看出調用原有的[DllImport("user32.Dll")]動態(tài)鏈接庫時無法滿足WinCE下程序要求,所以我們調用了[DllImport("coredll.Dll")]。希望這篇文章能給初學者提供一些捷徑。
C# Windows CE使用的一些感受和實例的介紹就向你介紹到這里,希望對你了解C# Windows CE使用有所幫助。
【編輯推薦】