1:引用4个API函数
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd,int hWndInsertAfter,int X,int Y,int cx,int cy,int uFlags );
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
2:在窗体的LOAD事件中添加取消令牌
CancellationTokenSource cancellationTokenSource; //声明字段
//LOAD事件中添加
cancellationTokenSource = new CancellationTokenSource();//添加取消令牌
ShowWindowAsync();//开始程序运行
3:添加方法设置窗体参数
public static void SetWindowPos(IntPtr hWnd)
{
//0x0010为不激活窗口,这个比较关键
SetWindowPos(hWnd, -1, 0, 0, 0, 0, 0x001 | 0x002 | 0x0010 | 0x040);
}
4:创建方法开始运行程序强制窗体靠前
private void ShowWindowAsync()
{
Task task = new Task(() =>
{
IntPtr hWnd = GetForegroundWindow();
while (!cancellationTokenSource.IsCancellationRequested)
{
if (hWnd != IntPtr.Zero || GetForegroundWindow() != hWnd)
{
//选中当前的句柄窗口
SetWindowPos(hWnd);
//SendKeys.SendWait(" ");
}
}
});
task.Start();
}