You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

选择应用窗口并通过PostMessage向DraftSight发送Enter键问题咨询

KeySimulator 开发说明与偶发识别问题修复

工具基础信息

  • 运行环境:Windows 虚拟机
  • 核心能力:自动定位同环境下运行的DraftSight软件,当软件弹出任意提示弹窗时自动发送Enter键完成确认
  • 可用保障:已配置系统任务计划,支持登录自动启动、异常退出自动拉起,可稳定7*24小时运行

现有实现问题根因

当前代码仅通过Qt类名匹配窗口,存在两个核心缺陷:

  1. FindWindow("Qt5QWindowIcon", null)只匹配类名,若虚拟机内同时运行其他基于Qt5开发的程序,会匹配到错误的窗口句柄
  2. 没有对返回的窗口句柄做非空校验,匹配失败时后续调用SetForegroundWindow、PostMessage会直接触发异常,可能导致程序崩溃退出

优化后实现代码

using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

const UInt32 WM_KEYDOWN = 0x0100;

// DraftSight窗口匹配逻辑
IntPtr draftSightHandle = IntPtr.Zero;
// 优先按类名+窗口标题关键词匹配,可根据实际DraftSight窗口标题调整关键词
draftSightHandle = FindWindow("Qt5QWindowIcon", "DraftSight");
// 匹配不到时遍历进程二次确认
if (draftSightHandle == IntPtr.Zero)
{
    foreach (Process process in Process.GetProcessesByName("DraftSight"))
    {
        draftSightHandle = process.MainWindowHandle;
        if (draftSightHandle != IntPtr.Zero)
        {
            break;
        }
    }
}
// 仅拿到有效句柄后执行后续操作
if (draftSightHandle != IntPtr.Zero)
{
    SetForegroundWindow(draftSightHandle);
    PostMessage(draftSightHandle, WM_KEYDOWN, (int)Keys.Enter, 0);
}

内容的提问来源于stack exchange,提问作者eugenebobalo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:18:01