In the project I am working on I have created an on screen keyboard which is meant to type into either TextBoxes or DataGridViewCells.
The way I am attempting to accomplish this is with a few methods and variables. First there is a global variable called CurrentFocus
which is an object that is set to be whatever object had the most recent focus that the keypad can type into. This variable was created because there doesn't seem to be a LastFocus
style method within VB.Net.
I am setting the value of CurrentFocus
by adding simple event handlers to the textboxes that I will be looking to type data in the following manner:
Dim randomTextbox As New Textbox
AddHandler randomTextbox.GotFocus, AddressOf TextboxGainsFocus
Private Sub TextboxGainsFocus(sender as Textbox, e As EventArgs)
CurrentFocus = sender
End Sub
As for typing into the textboxes themselves, each key on the keyboard calls the following method, with the parameter value being the uppercase of whatever key is being pressed (So pressing the 'B' key sends "B" as a parameter)
Private Sub KeypadPress(ByCal key As Char)
If TypeOf CurrentFocus Is TextBox Then
If Char.IsDigit(key) Then
CType(CurrentFocus, Textbox).Text &= key
Else
If shiftActive Then
CType(CurrentFocus, Textbox).Text &= key
Else
CType(CurrentFocus, Textbox).Text &= Char.ToLower(key)
End If
End If
End If
End Sub
I don't exactly have a way to easily set up a shift key that you hold down, so I've set up 'Shift' to be like Caps Lock where you just toggle it on or off. That is the purpose of the shiftActive
boolean value.
Now all of the above code works perfectly fine. My issue right now is I can't get it to work with DataGridViewCells. First I've tried adding a similar EventHandler to the datagrids I am using
Dim randomGrid As New DataGridView
AddHandler randomGrid.GotFocus, AddressOf GridGainsFocus
Private Sub GridGainsFocus(sender As DataGridView, e As EventArgs)
CurrentFocus = sender.CurrentCell
End Sub
And I have tried adding an ElseIf
case to the KeypadPress
method that detects when the CurrentFocus
is a DataGridViewCell. That works fine. My issue is that it either doesn't have the correct cell selected, or it just doesn't do anything.
For example let's say I have 3 rows and 3 columns in my DataGridView. I select Cell (2,2) and then press a key on my keypad. If I put a breakpoint in to see what the value of CurrentFocus
is when the KeypadPress
method fires, it shows CurrentFocus
as being Cell (0,0).
This doesn't always happen though. Sometimes I do get it randomly (and it does seem random) set as the proper Cell, but trying things like
CType(CurrentFocus, DataGridViewCell).Value &= key
In my Keypress method doesn't do anything to change the value of the DataGridViewCell.
So what exactly do I need to do? Is there a way to set up each Cell to have it's own handler and have it work that way? How would I make it so I can modify the value of the Cells themselves?
Thanks for the assistance.