WaitForInputIdle简介

本博客介绍了一个函数,用于启动新进程并等待其完成初始化,同时等待用户输入。详细展示了创建进程、初始化检查及错误处理的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

等待新进程完成它的初始化并等待用户输入。

例如:


BOOL StartProcess(char* strCmdLine)
{
    BOOL bRet = FALSE;
    STARTUPINFO sinfo;
    PROCESS_INFORMATION pinfo;
    memset(&sinfo, 0, sizeof(sinfo));
    sinfo.cb = sizeof(STARTUPINFO);

    char szDir[4];
    szDir[0] = strCmdLine[0];
    szDir[1] = strCmdLine[1];
    szDir[2] = 0;

    if (CreateProcess(0, strCmdLine, 0, 0, 0, 0, 0, szDir, &sinfo, &pinfo))
    {
        PushLog("进程已创建,等待初始化完成...");
        if (WaitForInputIdle(pinfo.hProcess, 30000) == 0)
        {
            PushLog("进程创建完成,初始化完毕");
            bRet = TRUE;
        }
        else
        {
            PushLog("%s在30秒内未初始化完成,或者有错误发生code=%d", strCmdLine, GetLastError());
        }
        CloseHandle(pinfo.hThread);
        CloseHandle(pinfo.hProcess);
    }

    if (bRet == FALSE)
    {
        DWORD_G dwErr = GetLastError();
        PushLog("%s在启动过程中有错误发生,code=%d", strCmdLine, dwErr);
    }
    return bRet;
}


using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; namespace WpfApp2 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); NotepadHost lControl = new NotepadHost(1, 1); HostElement.Child = lControl; } } // 自定义 HwndHost 类 public class NotepadHost : HwndHost { [DllImport("user32.dll")] private static extern int SetParent(IntPtr hWndChild, IntPtr hWndParent); [DllImport("user32.dll", SetLastError = true)] private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight, bool bRepaint); private int _width, _height; private Process notepadProcess; public NotepadHost(int width, int height) { _width = width; _height = height; } protected override HandleRef BuildWindowCore(HandleRef hwndParent) { // 启动记事本进程 notepadProcess = Process.Start("notepad.exe"); notepadProcess.WaitForInputIdle(); // 等待记事本启动完成 // 将记事本窗口嵌入到WPF中 if (notepadProcess != null && !notepadProcess.HasExited) { // 将记事本窗口设置为WindowsFormsHost的子窗口 SetParent(notepadProcess.MainWindowHandle, hwndParent.Handle); // 当TabItem尺寸变化时调整记事本窗口大小 this.SizeChanged += (s, e) => { if (!notepadProcess.HasExited) { MoveWindow(notepadProcess.MainWindowHandle, 0, 0, (int)this.ActualWidth, (int)this.ActualHeight, true); } }; } return new HandleRef(this, hwndParent.Handle); } protected override void DestroyWindowCore(HandleRef hwnd) { } protected override nint WndProc(nint hwnd, int msg, nint wParam, nint lParam, ref bool handled) { return base.WndProc(hwnd, msg, wParam, lParam, ref handled); } } }
最新发布
08-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值