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

Windows 11下VB.NET调用FindWindowEx无法找到记事本窗口求助

解决Windows 11下VB.NET查找记事本窗口失败的问题

问题根源

  1. 窗口类名变更:Windows 11的记事本主窗口类名已从Notepad改为NotepadWindowClass,旧代码用原类名自然找不到窗口。
  2. 窗口未就绪:启动记事本后立即执行查找操作,窗口可能还未完全创建完成,导致查找失败。
  3. API参数错误:原代码中FindWindowEx的hwndParent和hwndChild参数类型为Integer,在64位系统下会导致句柄截断;同时VM_SETTEXT的定义错误,正确值应为&HC(WM_SETTEXT消息的常量值)。

修正后的代码示例

Imports System.Runtime.InteropServices
Imports System.Diagnostics

Public Class Form1
    ' 修正FindWindowEx的参数类型,使用IntPtr兼容32/64位系统
    <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)>
    Private Shared Function FindWindowEx(
                                    ByVal hwndParent As IntPtr,
                                    ByVal hwndChildAfter As IntPtr,
                                    ByVal lpszClass As String,
                                    ByVal lpszWindow As String) As IntPtr
    End Function

    ' 导入SendMessage用于向编辑框发送文本
    <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
    Private Shared Function SendMessage(
                                    ByVal hWnd As IntPtr,
                                    ByVal Msg As Integer,
                                    ByVal wParam As IntPtr,
                                    ByVal lParam As String) As IntPtr
    End Function

    ' WM_SETTEXT消息常量
    Private Const WM_SETTEXT As Integer = &HC

    Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
        Dim source As String = "hello world"
        Dim p As New Process()
        p.StartInfo.FileName = "notepad.exe"
        p.Start()

        ' 等待记事本进程进入空闲状态,确保窗口已创建
        p.WaitForInputIdle()

        ' 查找Windows 11记事本主窗口(类名:NotepadWindowClass)
        Dim notepadHwnd As IntPtr = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "NotepadWindowClass", Nothing)

        If notepadHwnd <> IntPtr.Zero Then
            MessageBox.Show("找到记事本窗口")

            ' 查找记事本内的编辑控件(类名:Edit)
            Dim editHwnd As IntPtr = FindWindowEx(notepadHwnd, IntPtr.Zero, "Edit", Nothing)
            If editHwnd <> IntPtr.Zero Then
                ' 向编辑控件发送文本
                SendMessage(editHwnd, WM_SETTEXT, IntPtr.Zero, source)
            End If
        Else
            MessageBox.Show("未找到记事本窗口")
        End If
    End Sub
End Class

关键说明

  • 类名适配:Windows 11记事本主窗口类名是NotepadWindowClass,编辑控件的类名仍保持Edit,和Windows 10一致。
  • 等待窗口就绪:Process.WaitForInputIdle()会等待进程完成初始化并进入空闲状态,避免因窗口未创建完成导致的查找失败。
  • API参数修正:将FindWindowEx的父窗口、子窗口参数改为IntPtr,确保在64位系统下句柄不会被截断,保证兼容性。
  • 正确发送文本:需要找到记事本的编辑控件句柄,再发送WM_SETTEXT消息,直接向主窗口发送消息无效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:13:13