Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

sendkeys - Simple Application for sending Keystroke in VB.NET

I have an issue regarding Sendkeys Class, as i want to use this class in order to send some keystroke to the active application. As a first step i want to test the {Enter} keystroke, so in order to achieve that i made a simple application in vb.net 2010

Public Class Form1
Public Shared data As String
Private Sub SendintText(command As String)
    Try
        SendKeys.SendWait(command)
    Catch e As Exception
        MsgBox(e.StackTrace)
    End Try
End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    data = TextBox1.Text.ToString
    SendingText(data)
End Sub

End Class

When i tried to run for {Enter} i have received infinit loop error: An unhandled exception of type 'System.StackOverflowException' occurred in System.Windows.Forms.dll Could someone help me?

LATER EDIT : In meantime i have found another example

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    System.Threading.Thread.Sleep(2000)
    SendKeys.SendWait("{ENTER}")
End Sub

If in background i have two applications :

  1. Visual Studio
  2. Target application

How can i focus on the target application, because now when i am running the form , that form became active..is there any solution to call the winform from command prompt with some parameter (the key that i want to send)?

Later Edit2 strong text i have give it up the idea for windows form, so finnally i have made a simple program in console application that simulates the keystroke ... Imports System Imports System.Windows.Forms

Module Module1

Sub Main(ByVal args() As String)
    Dim data As String = args(0)
    Console.WriteLine("You insert the : {0}", data)
    System.Threading.Thread.Sleep(5000)
    SendKeys.SendWait(data)
End Sub

End Module

By the way in order to use double quotes in a parameter you need "test"...(i have spent 15 min to find out) so it might be usefull... Thanks again for the informations.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Button has focus. Button click event sends an enter keystroke. Sending an enter causes the button click event to fire. Infinite loop.

You could disable the button before and re-enable the button after the sendkeys routine is done to stop the infinite loop.

What you probably would want to do is switch the focus back to the application you want to send your keystrokes to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...