Windows Mobile 2003Pocket PC 2002Windows Mobile 5.NET CFWindows MobileVisual Studio 2005C# 2.0初学者开发Visual StudioWindows.NETC#
使用 CreateProcess 和 C# 以编程方式在 Windows Mobile 上启动可执行程序





4.00/5 (2投票s)
以下文章解释了如何在 Windows Mobile 应用程序中使用 C# 程序化地启动可执行文件。
引言
也许只是我个人的想法,但有许多时候我发现我需要在应用程序中启动(或 shell)一个可执行文件。大部分情况下,我需要这样做是为了启动一个数据同步客户端,但我相信还有许多其他原因需要在 Windows Mobile 上执行此操作。我有点惊讶的是,我发现很少有关于如何在 Windows Mobile 上执行此操作的示例。
虽然似乎有很多方法可以做到这一点,但我个人的偏好是使用 CreateProcess
。我喜欢它,因为它让我可以选择启动可执行文件并立即返回,或者我可以坐下来等待应用程序完成。
本文旨在解释我如何使用 CreateProcess
函数来启动一个可执行文件。如果您知道更好的方法,或者知道如何改进代码,我非常乐意听取您的意见。如果不是,我希望您觉得这段代码有帮助。
要求
要开始开发应用程序,需要以下工具
- Visual Studio .NET 2005
- Windows Mobile 5 软件开发工具包(标准版和专业版)
- Windows Mobile 5 设备或模拟器
Using the Code
该应用程序本身相当简单。您需要做的第一件事是在您的应用程序中添加对以下命名空间的引用
using System.Runtime.InteropServices;
完成此操作后,您还需要以下声明才能执行程序
public class ProcessInfo
{
public IntPtr hProcess;
public IntPtr hThread;
public IntPtr ProcessID;
public IntPtr ThreadID;
}
[DllImport("CoreDll.DLL", SetLastError = true)]
private static extern int CreateProcess(String imageName, String cmdLine,
IntPtr lpProcessAttributes, IntPtr lpThreadAttributes,
Int32 boolInheritHandles, Int32 dwCreationFlags, IntPtr lpEnvironment,
IntPtr lpszCurrentDir, byte[] si, ProcessInfo pi);
[DllImport("coredll")]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("coredll")]
private static extern uint WaitForSingleObject
(IntPtr hHandle, uint dwMilliseconds);
[DllImport("coredll.dll", SetLastError = true)]
private static extern int GetExitCodeProcess
(IntPtr hProcess, ref int lpExitCode);
此外,我们需要以下函数来更轻松地启动可执行文件。请注意使用 WaitForSingleObject
的那一行。如果您不想等待应用程序完成,可以注释掉该行。
private void LaunchApp(string strPath, string strParms)
{
ProcessInfo pi = new ProcessInfo();
byte[] si = new byte[128];
CreateProcess(strPath, strParms, IntPtr.Zero, IntPtr.Zero,
0, 0, IntPtr.Zero, IntPtr.Zero, si, pi);
// This line can be commented out if you do not want
// to wait for the process to exit
WaitForSingleObject(pi.hProcess, 0xFFFFFFFF);
int exitCode = 0;
GetExitCodeProcess(pi.hProcess, ref exitCode);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return;
}
现在启动应用程序很简单。以下行将使用适当的参数启动可执行文件
LaunchApp(textEXE.Text, textParms.Text);
历史
- 2007 年 7 月 4 日:初始发布