6 Replies - 1302 Views - Last Post: 24 October 2012 - 03:17 PM Rate Topic: -----

#1 NewK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 07-October 12

How to use a Key to automatically press Enter and enter text?

Posted 22 October 2012 - 07:19 PM

Ok, so before I state my problem I just want to say that I'm not doing any kind of spammer nor am I going to use this code maliciously, I just need to automate some boring mundane tasks.

So what I wanted to do is: When I press the key F9 for example, the program would automatically "press" the enter key and write some text in an active program (notepad,word,etc..)

I tried doing this with the KeyDown event but it didn't work, here's my code:
Public Class Form1

    Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If e.KeyCode = Keys.F9 Then
            SendKeys.Send("{Enter}") 
            SendKeys.Send("You pressed F9")
        End If
    End Sub
End Class



Can anyone tell me what I did wrong?

Is This A Good Question/Topic? 0
  • +

Replies To: How to use a Key to automatically press Enter and enter text?

#2 lar3ry  Icon User is offline

  • Coding Geezer
  • member icon

Reputation: 310
  • View blog
  • Posts: 1,290
  • Joined: 12-September 12

Re: How to use a Key to automatically press Enter and enter text?

Posted 22 October 2012 - 09:11 PM

View PostNewK, on 22 October 2012 - 07:19 PM, said:

I tried doing this with the KeyDown event but it didn't work, here's my code:


Try:
    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Me.KeyPreview = True
    End Sub


Was This Post Helpful? 1
  • +
  • -

#3 NewK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 07-October 12

Re: How to use a Key to automatically press Enter and enter text?

Posted 23 October 2012 - 02:08 PM

View Postlar3ry, on 22 October 2012 - 09:11 PM, said:

View PostNewK, on 22 October 2012 - 07:19 PM, said:

I tried doing this with the KeyDown event but it didn't work, here's my code:


Try:
    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Me.KeyPreview = True
    End Sub


Thanks for replying, that worked but only inside the program, I added a rich textbox inside the program to test it and it worked. However if I press F9 and then put the cursor on a notepad or any text box outside the program it doesn't write anything like I wanted to. Do you know what I could be doing wrong?
Was This Post Helpful? 0
  • +
  • -

#4 lar3ry  Icon User is offline

  • Coding Geezer
  • member icon

Reputation: 310
  • View blog
  • Posts: 1,290
  • Joined: 12-September 12

Re: How to use a Key to automatically press Enter and enter text?

Posted 23 October 2012 - 10:20 PM

Sorry, I don't know. You would have to run a program as a service that intercepts all keys, and pass them on, and I have no idea where to even start doing that.
Was This Post Helpful? 1
  • +
  • -

#5 lucky3  Icon User is offline

  • Friend lucky3 As IHelpable
  • member icon

Reputation: 231
  • View blog
  • Posts: 765
  • Joined: 19-October 11

Re: How to use a Key to automatically press Enter and enter text?

Posted 24 October 2012 - 12:49 AM

I wanted to help here, but now it seems I need some help too ;)

Disclaimer: when it gets unresponsive, use Ctrl+Alt+Delete (works for me).

You need empty Windows Forms project, and this code (please view the question below the code):
Imports System.Runtime.InteropServices

Public Class Form1

    Dim WindowHandle As IntPtr
    Dim WindowID As IntPtr
    Dim txtKeyPressEHashCodes As TextBox


    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Me.KeyPreview = True
        Me.WindowState = FormWindowState.Maximized
        Process.Start("notepad.exe")
        Threading.Thread.Sleep(1000)
        WindowHandle = FindWindow(Nothing, "Untitled - Notepad")
        WindowID = GetWindowThreadProcessId(WindowHandle, IntPtr.Zero)

        txtKeyPressEHashCodes = New TextBox With {.Multiline = True, .Dock = DockStyle.Fill, .ScrollBars = ScrollBars.Vertical}
        Me.Controls.Add(txtKeyPressEHashCodes)
    End Sub

    Private Sub Form1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
        If e.Handled = False And e.KeyChar <> Nothing Then
            SetForegroundWindow(WindowHandle)
            Try
                txtKeyPressEHashCodes.AppendText(e.GetHashCode & Environment.NewLine)
                SendKeys.Send(e.KeyChar)
                e.Handled = True
            Catch ex As Exception
                e.Handled = False
            End Try
        End If

        If Not Me.Focused AndAlso e.Handled Then
            Me.Focus()
        End If
    End Sub

    <System.Runtime.InteropServices.DllImport("user32.dll")>
    Public Shared Function FindWindow( _
       ByVal lpClassName As String, _
       ByVal lpWindowName As String) As IntPtr
    End Function

    <System.Runtime.InteropServices.DllImport("user32.dll")>
    Public Shared Function GetWindowThreadProcessId(
        ByVal hWnd As IntPtr,
        ByVal lpwdProcessId As IntPtr) As IntPtr
    End Function

    <System.Runtime.InteropServices.DllImport("user32.dll")>
    Public Shared Function ShowWindow(
       ByVal hWnd As IntPtr,
       ByVal nCmdShow As Integer) As Boolean
    End Function

    <System.Runtime.InteropServices.DllImport("user32.dll")>
    Public Shared Function SetForegroundWindow(ByVal hWnd As IntPtr) As Boolean
    End Function
End Class



Why doesn't Form stay focused?
Was This Post Helpful? 0
  • +
  • -

#6 lucky3  Icon User is offline

  • Friend lucky3 As IHelpable
  • member icon

Reputation: 231
  • View blog
  • Posts: 765
  • Joined: 19-October 11

Re: How to use a Key to automatically press Enter and enter text?

Posted 24 October 2012 - 03:38 AM

Ok, I played a little with this, and here is something, you can start working on. Just make a new Windows Form project, and paste all the code in it. You'll get the feeling how to send keys around (I hope):

Public Class Form1
    Private notepadProcess As Process = Nothing
    Private processID As Integer

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Initialize()
    End Sub

    Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click
        Try
            notepadProcess = Process.GetProcessesByName("notepad").First
        Catch ex As Exception
            Process.Start("notepad.exe")
            notepadProcess = Process.GetProcessesByName("notepad").First
            Threading.Thread.Sleep(1000) 'let's give the Notepad time to initialize
        Finally
            processID = notepadProcess.Id
        End Try

        AppActivate(processID)
        SendKeys.SendWait(txtInput.Text)
        Me.Activate()
    End Sub


#Region "Form Designer generated code"
    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub Initialize()
        Me.txtInput = New System.Windows.Forms.TextBox()
        Me.btnSend = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'txtInput
        '
        Me.txtInput.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
            Or System.Windows.Forms.AnchorStyles.Left) _
            Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.txtInput.Location = New System.Drawing.Point(12, 12)
        Me.txtInput.Multiline = True
        Me.txtInput.Name = "txtInput"
        Me.txtInput.Size = New System.Drawing.Size(458, 259)
        Me.txtInput.TabIndex = 0
        '
        'btnSend
        '
        Me.btnSend.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.btnSend.Location = New System.Drawing.Point(395, 288)
        Me.btnSend.Name = "btnSend"
        Me.btnSend.Size = New System.Drawing.Size(75, 23)
        Me.btnSend.TabIndex = 1
        Me.btnSend.Text = "Send!"
        Me.btnSend.UseVisualStyleBackColor = True
        '
        'Form1
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(482, 323)
        Me.Controls.Add(Me.btnSend)
        Me.Controls.Add(Me.txtInput)
        Me.Name = "Form1"
        Me.Text = "Send Input To Notepad Example by lucky3"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents txtInput As System.Windows.Forms.TextBox
    Friend WithEvents btnSend As System.Windows.Forms.Button
#End Region

End Class



This post has been edited by lucky3: 24 October 2012 - 07:11 AM

Was This Post Helpful? 2
  • +
  • -

#7 NewK  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 07-October 12

Re: How to use a Key to automatically press Enter and enter text?

Posted 24 October 2012 - 03:17 PM

Thanks for all your help guys, but after researching on this I found out a simpler way to do this by using Global Hotkeys and calling the user32.dll library. After reading some tutorials about global hotkeys I was able to google a simpler way to do this. Here's my code after I called the user32.dll file:

Public Class Form1

    Private Declare Function GetKeyPress Lib "user32" Alias "GetAsyncKeyState" (ByVal key As Integer) As Integer


    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        If GetKeyPress(Keys.F9) Then
            SendKeys.Send("{Enter}")
            SendKeys.Send("You pressed F9")
        End If
    End Sub

End Class


This worked exactly how I wanted it to, it worked outside the program, on the notepad,word, etc.... and it also worked when the program was not focused.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1