WaitForInputIdle

本文详细介绍了Windows系统中用于等待进程初始化完成并等待用户输入的函数WaitForInputIdle的使用方法,包括其参数、返回值和应用场景。了解此函数对于实现进程间同步和等待用户响应具有重要意义。
函数原型  DWORD WaitForInputIdle(
  HANDLE hProcess,
  DWORD dwMilliseconds
  );

编辑本段函数作用

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

编辑本段参数

  hProcess
  [in] 进程的句柄。如果这个进程是一个控制台应用程序或者没有消息队列,函数立刻返回。
  dwMilliseconds
  [in] 超时间隔,单位为毫秒。如果 dwMilliseconds 设为 INFINITE,函数会一直等到进程空闲即初始化完成后才返回。

编辑本段返回值

  
返回值说明
0线程初始化成功,等待结束。
WAIT_TIMEOUT等待强制结束,线程初始化超出dwMilliseconds 。
WAIT_FAILED出错。会设置GetLastError。

编辑本段说明

  该函数可以使一个线程挂起,直到规定线程初始化完成,等待用户输入。这对于父进程和子进程之间的同步是极其有用的,因为 CreateProcess函数不会等待新进程完成它的初始化工作。在试图与子线程通讯前,父线程可以使用 WaitForInputIdle来判断子线程是否已经初始化完成。举例来说,在试图与新进程关联的窗口之前,进程应该先调用 WaitForInputIdle

编辑本段使用需求

  头文件:Winuser.h,Windows.h。
  链接库:User32.lib。
  DLL需求:User32.dll。
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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值