2008年9月25日 星期四

用PostMessage如何自動控制記事本?

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Const SW_SHOWNORMAL = 1
Const WM_CLOSE = &H10
Const WM_KEYDOWN = &H100
Const gcClassnameMSWord = "OpusApp"
Const gcClassnameMSExcel = "XLMAIN"
Const gcClassnameMSIExplorer = "IEFrame"
Const gcClassnameMSVBasic = "wndclass_desked_gsk"
Const gcClassnameNotePad = "Notepad"
Const gcClassnameMyVBApp = "ThunderForm"

Private Declare Function GetWindow Lib "user32" ( _
ByVal hwnd As Long, _
ByVal wCmd As Long) As Long
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 GW_CHILD = 5
Private Const WM_SETTEXT = &HC

Private Sub Command1_Click()
Dim WinWnd As Long, Ret As String, RetVal As Long, lpClassName As String
Dim txthWnd As Long

WinWnd = FindWindow(vbNullString, "1.txt - 記事本")
ShowWindow WinWnd, SW_SHOWNORMAL
lpClassName = Space(256)

'這才是那個文本框的句柄!!!!
txthWnd = GetWindow(WinWnd, GW_CHILD)
'GetClassName txthWnd, strCLSName, 10
'Debug.Print strCLSName
'你可以把上面兩句不註釋了,看看得到是不是Edit在 立即窗口


PostMessage txthWnd, WM_KEYDOWN, 65, 0&
'這兩種方法都可以
SendMessage txthWnd, WM_SETTEXT, 0, ByVal "A"

'PostMessage WinWnd, WM_KEYDOWN, 65, &H1110001 '失敗
'PostMessage WinWnd, WM_CHAR, "A", 0& '失敗
'PostMessage WinWnd, WM_CLOSE, 0&, 0& '可實現
End Sub

0 留言:

張貼留言