如何在VB中打开一个记事本窗口并获取窗口句柄,向其中发送富文本框中的内容(最好带格式)

2024-12-05 05:20:05
推荐回答(4个)
回答1:

1.新建三个命令按钮Command1命名“写字”,Command1命名“禁用”,Command1命名“关闭”;2.在窗体写下如下代码:
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function EnableWindow Lib "user32" (ByVal hwnd As Long, ByVal fEnable As Long) As Long
'该程序在VB6.0下由shumu_qing测试通过
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Const WM_CLOSE = &H10
Private Const WM_SETTEXT = &HC
Private Sub Command1_Click()
Dim WindowHandle As Long, ChildWindowHandle As Long
WindowHandle = FindWindow(vbNullString, "无标题 - 记事本")

If WindowHandle Then '如果获取句柄成功
ChildWindowHandle = FindWindowEx(WindowHandle, 0, "Edit", vbNullString)

If ChildWindowHandle Then '如果成功获取子句柄
SendMessage ChildWindowHandle, WM_SETTEXT, 0, ByVal CStr("hello") '发送hello消息
Else
MsgBox "无法获取子窗口", vbCritical, "提示"
End If
Else
MsgBox "无法获取窗口", vbCritical, "提示"
End If
End SubPrivate Sub Command2_Click()
Dim WindowHandle As Long, ChildWindowHandle As Long
WindowHandle = FindWindow(vbNullString, "无标题 - 记事本")

If WindowHandle Then '如果获取句柄成功
ChildWindowHandle = FindWindowEx(WindowHandle, 0, "Edit", vbNullString)

If ChildWindowHandle Then '如果成功获取子句柄
EnableWindow ChildWindowHandle, False '禁用子窗口
Else
MsgBox "无法获取子窗口", vbCritical, "提示"
End If
Else
MsgBox "无法获取窗口", vbCritical, "提示"
End If
End SubPrivate Sub Command3_Click()
Dim WindowHandle As Long
WindowHandle = FindWindow(vbNullString, "无标题 - 记事本")

If WindowHandle Then '如果获取句柄成功
SendMessage WindowHandle, WM_CLOSE, 0, 0 '关闭窗口
Else
MsgBox "无法获取窗口", vbCritical, "提示"
End If
End Sub

回答2:

楼上代码非常麻烦首先打开记事本你可以直接用SHELL函数打开,并且返回句柄。这样就可以了,完全不用FINDWINDOW这个API函数,然后发送内容先用appactive激活窗口再用sendkeys函数发送就行了。具体代码不写了,很简单。学过VB的都会写。 另外说以下 API函数能不用尽量不用。VB调用API函数效率其实很低的。

回答3:

楼上还是不要误导新手,与其用vb自身函数反复调用vb库不必要的垃圾代码,还不如直接用api效率高

回答4:

直接用OPEN语句创建一个TXT文件,写入内容,然后在用SHELL语句打开新建的TXT就可以了。