We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,539 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Handle keystrokes from Form1 and Form2 in Form1

My application has two forms.
Focus may be on either form.
Keypresses on either Form1 or on Form2 need to processed by code in Form1.vb.
How should I make this happen?

Thank you
retroMIDI2

2
Contributors
1
Reply
16 Minutes
Discussion Span
3 Months Ago
Last Updated
2
Views
retroMIDI2
Newbie Poster
1 post since Jan 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

Here's one way:

Public Class Form1

    Public Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        Dim CurrentForm As Form = DirectCast(sender, Form)
        MsgBox(e.KeyChar.ToString + " " + CurrentForm.Name)
    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AddHandler Me.KeyPress, AddressOf Form1_KeyPress
        Form2.Show()
    End Sub

End Class

Public Class Form2

    Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AddHandler Me.KeyPress, AddressOf Form1.Form1_KeyPress
    End Sub
End Class

Set the KeyPreview property to true on each form. When you run this whichever form has the focus will echo the key pressed and the form name to the messagebox.

tinstaafl
Nearly a Posting Virtuoso
1,289 posts since Jun 2010
Reputation Points: 341
Solved Threads: 223
Skill Endorsements: 14

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0558 seconds using 2.66MB