.net随笔-vb2015打开外部程序发送键盘信号(3)

使用DllImport

Imports System.Runtime.InteropServices
Public Class Form1

    <DllImport("user32.DLL", EntryPoint:="FindWindow")>
    Private Shared Function FindWindow(
        ByVal lpClassName As String,
        ByVal lpWindowName As String) As Integer
    End Function
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim hWnd As Integer
        Dim ProcID As Integer

        ' 通过shell函数运行一个新实例
        ProcID = Shell("CALC.EXE", AppWinStyle.NormalFocus)
        hWnd = FindWindow(vbNullString, "计算器")
        If hWnd Then
            MessageBox.Show("找到计算器")
        Else
            MessageBox.Show("没找到计算器")
        End If

    End Sub

End Class

Declare Auto Function

Public Class Form1
    Private Declare Auto Function FindWindow Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim hWnd As Integer
        Dim ProcID As Integer

        ' 通过shell函数运行一个新实例
        ProcID = Shell("CALC.EXE", AppWinStyle.NormalFocus)
        hWnd = FindWindow(vbNullString, "计算器")
        If hWnd Then
            MessageBox.Show("找到计算器")
        Else
            MessageBox.Show("没找到计算器")
        End If

    End Sub

End Class

.net随笔-vb2015打开外部程序发送键盘信号(3)

Imports System.Runtime.InteropServices


Public Class Form1


    Private Declare Auto Function FindWindow Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
    Private Declare Auto Function FindWindowEx Lib "user32" (ByVal hWndParent As Integer, ByVal hWndChildAfter As Integer, ByVal lpszClass As String, ByVal lpszWindow As String) As Integer

    Private Declare Auto Function SetForegroundWindow Lib "user32" (ByVal hWnd As Integer) As Integer
    Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA"(ByVal hWnd As Integer, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As String) As Integer
    Private Const WM_SETTEXT As Integer = &HC



    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


        ' 通过shell函数运行一个新实例
        Shell("notepad.EXE", AppWinStyle.NormalFocus)
        Dim hWnd As Integer = FindWindow(vbNullString, "无标题 - 记事本")

        If hWnd Then
            SendMessage(hWnd, WM_SETTEXT, 0, Trim(TextBox1.Text))
            Dim myhwnd As Integer = FindWindowEx(hWnd, IntPtr.Zero, "Edit", "")
            If myhwnd Then
                SendMessage(myhwnd, WM_SETTEXT, 0, Trim(TextBox2.Text))
            Else
                MessageBox.Show("没找到记事本编辑")
            End If
        Else
            MessageBox.Show("没找到记事本")
        End If


    End Sub


End Class

.net随笔-vb2015打开外部程序发送键盘信号(3)