C# Windows CE使用的一些感受:使用Windows的开发机上用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、

有时候我们会希望我们的程式只被执行一次,VB的时代我们会用App.PrevInstance,而.net的时代我们可以用下列方式实现

[STAThread]  


 


staticvoidMain()  


 


{  


 



//如果跟本程式命名的行程只有一个才执行程式  



 



if(System.Diagnostics.Process.  



GetProcessesByName(  


 


Application.ProductName).Length==1)  


 


{  


 


Application.Run(newForm1());  


 


}  


 


} 

但此方法在WinCE下无法实现,所以我们还是要先调用动态链接库,

[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组和起来应付一下。