VB编写应用程序,将串口数据转换为键盘口的输出
通过一台计算机的串口向另一台计算机的记事本中输入数据。也就是说主机A不断通过自己的串口发数据,这些数据以主机B键盘的形式显示在主机B的记事本上。
也就是主机B先接收串口数据,然后转为为键盘的输出,再在记事本上显示出来。
[解决办法]
写一个程序,接收串口数据,通过 API 转成键盘消息。
[解决办法]
当然,实际上写外部程序窗口(包括记事本界面)不一定非用键盘消息,可以通过 API 直接写的。
[解决办法]
Public Declare Function GetCaretPos Lib "user32" (lpPoint As POINTAPI) As Long
Public Declare Function GetForegroundWindow Lib "user32" () As Long
Public Declare Function GetFocus Lib "user32" () As Long
Public Declare Function ClientToScreen Lib "user32" (ByVal hwnd As Long, lpPoint As POINTAPI) As Long
Private Function CaretPos() As POINTAPI
Dim ptr As Long
ptr = GetForegroundWindow()
Dim p As POINTAPI
Dim targetThreadID, localThreadID As Long
'得到Caret在屏幕上的位置
If ptr <> 0 Then
targetThreadID = GetWindowThreadProcessId(ptr, 0)
localThreadID = GetCurrentThreadId()
If localThreadID <> targetThreadID Then
Call AttachThreadInput(localThreadID, targetThreadID, 1)
ptr = GetFocus()
If (ptr <> 0) Then
Call GetCaretPos(p)
Call ClientToScreen(ptr, p)
End If
Call AttachThreadInput(localThreadID, targetThreadID, 0)
End If
End If
CaretPos = p
End Function
Private Sub MSComm1_OnComm()
Dim Pos As POINTAPI
Dim hResult As Long
Dim hwnd As Long
Dim Str As String
Dim i As Integer
Select Case MSComm1.CommEvent
Case comEvReceive
'获得当前光标位置
Pos = CaretPos
'获得光标对应窗口的句柄
hwnd = WindowFromPoint(Pos.x, Pos.y)
Str = MSComm1.Input
'当激活窗口不是监控程序所处的窗口时,输出串口输入
If hwnd <> Me.hwnd Then
For i = 1 To Len(Str)
SendMessage hwnd, WM_IME_CHAR, Asc(Mid(Str, i, 1)), 1
Next
End If
MSComm1.PortOpen = False
End Select
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 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_PASTE = &H302
Private Const WM_SETTEXT = &HC
Private Sub Command1_Click()
Dim TemphWnd As Long
TemphWnd = FindWindow("Notepad", vbNullString)
TemphWnd = FindWindowEx(TemphWnd, 0, "Edit", vbNullString)
If TemphWnd Then
''-- 将Text1中的文本粘贴到记事本
'VB.Clipboard.SetText Text1.Text
'SendMessage TemphWnd, WM_PASTE, 0, ByVal 0&
'把记事本的内容设置为Text1中的文本
SendMessage TemphWnd, WM_SETTEXT, 0, ByVal CStr(Text1.Text)
End If
End Sub