Hi,
I have the following code in my “KeyDown” Event Handler for a set of TextFields. I am presuming that it is unwise to have 2 if statements for the same key - so is it possible to combine the two Chr(9) if statements?
[code] If index = 0 Then
Dim sound As Boolean = False
if Key = Chr(9) Then PopupMenu2.SetFocus
if Key = Chr(9) Then sound = False
if sound = True Then Beep
Return sound
End if[/code]
I tried the following code, but then the sound is false, no matter which key is depressed.
[code] If index = 0 Then
Dim sound As Boolean = False
if Key = Chr(9) Then PopupMenu2.SetFocus
sound = False
if sound = True Then Beep
Return sound
End if[/code]
Thank you all in advance.
If Key = chr(9) Then
Popupmenu2.SetFocus
Sound = False
End If
I knew it would be something ridiculously simple !
Thank you very much.
Just a comment, “Sound” is never True by any of those codes.
Not sure, but by the code looks like that you want to do the following:
If index = 0 Then
If Key = Chr(9) Then
PopupMenu2.SetFocus // index 0 and tab, setfocus on popup
Return False // and return false
End If
Beep
Return True // If index 0 and other key, beep and return True
End if
Yeah, I was only showing how to do the if structure with multiple statements.
I tend to do the following
[code]Dim bReturn As Boolean=True //set the return value to its default value
If index = 0 Then
If Key = Chr(9) Then
PopupMenu2.SetFocus // index 0 and tab, setfocus on popup
bReturn = False // set the return value for this situation
End If
if bReturn = True then Beep // If index 0 and other key, beep
End If
Return bReturn[/code]
I do this because I prefer to have only one exit point from my code (instead of several Returns)
I use early returns because optimization. This case, fewer CPU cycles and less memory footprint due to avoiding extra variable allocation, setting variable, consulting the variable again and maybe some cycles from deallocation.
Although I will use early returns depending on the situation, I prefer a single exit point, especially in longer methods, to prevent debugging issues later. For example, if I need to do cleanup, I don’t want to forget and exit earlier in the code.
Generally my longer methods follow an outline like:
if badCondition then return
if anotherBadCondition then return
// etc
dim r as boolean = true
if r then
// Some code that will set r to false if needed
end if
if r then
// More code that will set r to false if needed
end if
if r then
// You get the idea
end if
// Cleanup, if any
return // Or return a value set in a variable earlier
As you know, it’s a trade. Choose wisely and document your program as necessary.