I am having a problem with the .Net RichText control.
I am writing an application that relies heavily on the RichText control for user input in a form design app.
When the user presses CTL + I, I need to set the font style to Italic. I wrote code to override the KeyPress function. It works, but a Tab Char is also inserted into the text even though I set the Handeled property to true.
(CTL + B for bold and CTL + U for underline work fine)
CTL + I is ASCII code 9, which of course is a Horizontal Tab. However, if the .Handled property is set to true I would expect the RichText control to thow out the character. What am I missing Is this a bug I don't have $99.00 to find out so I hope someone can help. I will certainly appreciate it.
Best Regards,
-Marty

RichEdit Control and CTL + I Key combination
Carol Pahl
In this case, the insertion of the horizontal tab is occuring in the KeyPress event, rather than the KeyDown event (which is where things like copy/cut/paste are handled). For your code you work, you will have to handle both events:
'First, you need a class wide variable to determine if the KeyDown event handled the KeyPress event
Dim DidHandle As Boolean = False
'Now you put the code to do the italics on KeyDown
Private Sub RichTextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles RichTextBox1.KeyDown
If e.KeyCode = Keys.I And e.Control = True Then
Dim TargetStyle As FontStyle = RichTextBox1.SelectionFont.Style
If RichTextBox1.SelectionFont.Italic Then
TargetStyle -= FontStyle.Italic
Else
TargetStyle += FontStyle.Italic
End If
RichTextBox1.SelectionFont = New System.Drawing.Font(RichTextBox1.SelectionFont, TargetStyle)
e.Handled = True
'Set the variable to say we handled this key press
DidHandle = True
End If
End Sub
'Now put code in the KeyPress event to check for the key being handled in KeyDown
Private Sub RichTextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles RichTextBox1.KeyPress
If DidHandle Then
'Mark this key event as handled
e.Handled = True
'Reset our class wide variable
DidHandle = False
End If
End Sub
As you can see, you don't have to actually override the events, just handle them. By handling both events you'll get the desired results.
Good Luck!
HannesThor
Whenever an key event doesn't work like I expect, the first thing I do is move my code to the other key events and look for a difference... more trial and error than anything. But hey, so long as the errors won't end in death, it's a viable way to learn!! =)
Paul2006
Best Regards,
-Marty