最近在公司电脑用输入法时,总是会失去焦点,窗口内容在输入一半时就会跳到别的窗口,于是写了个软件监控一下到底是哪个小可爱在抢夺窗口的控制权。
环境:winform4.7.2
代码如下:在界面上记得加个label,并修改名称为lblProcessInfo
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class MainForm : Form
{
// 导入Windows API
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint processId);
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int Width, int Height, uint Flags);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetConsoleWindow();
// 置顶窗口标志
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private static readonly uint SWP_NOMOVE = 0x0002;
private static readonly uint SWP_NOSIZE = 0x0001;
public MainForm()
{
InitializeComponent();
// 设置窗口为置顶
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
// 启动定时器,每隔一秒检查一次焦点窗口
Timer timer = new Timer();
timer.Interval = 1000; // 每秒一次
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
// 获取当前前景窗口句柄
IntPtr foregroundHwnd = GetForegroundWindow();
// 获取前景窗口的进程 ID
uint processId;
GetWindowThreadProcessId(foregroundHwnd, out processId);
try
{
// 获取进程对象
Process process = Process.GetProcessById((int)processId);
// 获取应用程序的详细信息
string processName = process.ProcessName;
string filePath = process.MainModule.FileName;
// 更新窗体上的标签信息
lblProcessInfo.Text = $"窗口句柄: {foregroundHwnd}\n" +
$"进程 ID: {processId}\n" +
$"应用程序名称: {processName}\n" +
$"执行路径: {filePath}";
}
catch (Exception ex)
{
// 异常处理,无法获取进程信息
lblProcessInfo.Text = $"无法获取进程信息: {ex.Message}";
}
}
// 窗体加载事件
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// 设置窗体大小和初始位置
this.Size = new System.Drawing.Size(400, 300);
this.StartPosition = FormStartPosition.CenterScreen;
this.Text = "焦点窗口监控器";
}
}
}
然后继续做输入,果然发现了,是WPS2016在捣乱,真是个小可爱,果断卸载,解决问题