System.Windows.Forms.TreeView Node "not clickable" - vb.net

I've got a System.Windows.Forms.TreeView with HotTracking = True
I wish to set HotTracking to False only in a specific Node.
For example i would like the father to be not clickable and the children to be clickable.
Thank you

"Clickable" is pretty ambiguous. I'll assume you don't want them to be selectable. Which is easy to do with the BeforeSelect event, you can cancel it. For example:
Private Sub TreeView1_BeforeSelect(ByVal sender As Object, ByVal e As TreeViewCancelEventArgs) Handles TreeView1.BeforeSelect
If e.Node.Nodes.Count > 0 Then e.Cancel = True
End Sub
This does not make for a great user interface, the user will be very confuzzled when his click has no effect. You can make it a bit more intuitive by not throwing the click away and automatically selecting a node that you do allow to be selected. Make that look similar to this:
Private Sub TreeView1_BeforeSelect(ByVal sender As Object, ByVal e As TreeViewCancelEventArgs) Handles TreeView1.BeforeSelect
If e.Node.Nodes.Count > 0 Then
e.Cancel = True
Me.BeginInvoke(New Action(Of TreeNode)(AddressOf SelectNode), e.Node.Nodes(0))
End If
End Sub
Private Sub SelectNode(ByVal node As TreeNode)
node.Expand()
node.TreeView.SelectedNode = node
End Sub

Related

How to share events between forms

So i have a tray icon that should behave the same way between 3 forms. I then created this code:
Private Sub TrayForm_MouseClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseClick
If e.Button = MouseButtons.Right Then
If Not Application.OpenForms().OfType(Of TrayForm).Any = 1 Then
TrayForm.ContextMenuStrip1.Show(Cursor.Position)
End If
End If
End Sub
Which is used to handle the tray icon. How can i do to share this event between the forms so i don't have to place this same code on every form?
How are event handlers working exactly? I looked online and on MSDN and it is not clear to me.
Thanks
Are you sure that you want to share the event, and not juste the code that will handle the event?
If you don't want to copy and paste your code, which you need to handle the events of more than one form, here's a way to do it:
Declare the sub which contains the code needed to handle the event as a public shared sub. Like this:
Public Shared Sub TrayForm_MouseClick(sender As Object, e As MouseEventArgs)
So, now you have a Sub which can handle the event you want to handle from all three forms.
Now, when you initialize those forms, add a line to make the shared Sub handle the event you want it to handle:
AddHandler NotifyIcon1.MouseClick, AddressOf ProjectName.FileName.TrayForm_MouseClick
ProjectName.FileName is meant here to be the path to refer to the shares Sub inside the file where you put it. I usually name it like ProjectNameUtils.vb or something like that.
If you just want to avoid copy and pasting your Sub so you don't have to modify it at several places every time you change something, this could be a way to achieve that.
As Stipulated by Hans Passant:
Sub Eclass_EventHandler(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
If e.Button = MouseButtons.Right Then
If Not Application.OpenForms().OfType(Of TrayForm).Any = 1 Then
Me.ContextMenuStrip1.Show(Cursor.Position)
End If
End If
End Sub
On the Trayform.VB just did the trick.
But about the shared event. i Have one that would have to be:
Private Sub FormClosingEVENT(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
If Not FromMenu Then e.Cancel = True
Me.WindowState = FormWindowState.Minimized
'Application.Exit()
End Sub
How should i handle this?

Why DateTimePicker won't trigger keyDown and KeyPress events with the tab key?

Fellows, I am having this problem - the DateTimePicker won't trigger KeyDown and KeyPress events with the tab key (other keys are working fine, and the keyUp event as well, although it triggers after "arriving" at the DateTimePicker after pressing tab at the previous control focused). I'm using .net 4.6.1, Visual Basic and VS 2017.
What I'm trying to do -> Go to month and year directly on DateTimePicker in C# (Go to month and year directly on DateTimePicker)
Code I'm using:
Private Sub DateTimePicker1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DateTimePicker1.KeyDown
If e.KeyCode = Keys.Tab Then
e.Handled = True
MsgBox("TAB DOWN")
End If
End Sub
Private Sub DateTimePicker1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles DateTimePicker1.KeyPress
e.Handled = True
MsgBox("tab press")
End Sub
Private Sub DateTimePicker1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DateTimePicker1.KeyUp
If e.KeyCode = Keys.Tab Then
MsgBox("TAB UP")
e.Handled = True
End If
End Sub
Any clues?
The Tab key is used for navigation. Moving the focus from one control to another. So your KeyDown event handler can never see it, the keystroke is intercepted and used before that. You could subscribe the PreviewKeyDown event and set the e.IsInputKey = true as a workaround, check the MSDN sample code in the linked article for code.
But it is the wrong event to use anyway, you'd still want this to work when the user changes focus with the mouse instead of the keyboard. So use the Enter event instead.
Do beware that both approaches have the same problem, the focus might already be on the month part from previous usage of the control so now your code will incorrectly move it to the year part. And you can't find out what part has the focus, that is up a creek without a good paddle. A very ugly workaround for that is to change the Format property, and back, that forces the control to re-create the control window and that always resets the focus. Use BeginInvoke() to run that code. Perhaps more constructively, consider to just not display the day if you are only interested in month+year, CustomFormat property.
Sample code that implements the focus hack:
Private Sub DateTimePicker1_Enter(sender As Object, e As EventArgs) Handles DateTimePicker1.Enter
Me.BeginInvoke(
New Action(Sub()
'' Hack to reset focus
DateTimePicker1.Format = DateTimePickerFormat.Long
DateTimePicker1.Format = DateTimePickerFormat.Short
DateTimePicker1.Focus()
SendKeys.Send("{Right}")
End Sub))
End Sub
It's not the right answer to this question, although it helps as well. If you want to just make the tab behave as the right key when inside a DateTimePicker, a good (sketchy) way to do is:
Private i = 2
Protected Overrides Function ProcessTabKey(ByVal forward As Boolean) As Boolean
Dim ctl As Control = Me.ActiveControl
If ctl IsNot Nothing AndAlso TypeOf ctl Is DateTimePicker And i <> 0 Then
SendKeys.Send("{Right}")
i -= 1
Return True
End If
i = 2
Return MyBase.ProcessTabKey(forward)
End Function
You need to override ProcessCmdKey function
Private isTab As Boolean = False
Private isShiftTab As Boolean = False
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
If keyData = Keys.Tab Then
isTab = True
'Do something with it.
Else
isTab = False
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function

Button of UserControl vanishes when program is debugged

My UserControl button disappears when I debug my program. I have checked the code including the designer.vb code countless times there's nothing that makes the button .enabled = false or .visible = false. Any ideas why this is happening?
On my UserControl:
Private Sub btn_Begin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Begin.Click
Start_Race()
End Sub
Public Sub Start_Race()
TimeNow(Past_Time)
TimeNow(Start_Time)
lbl_Start_Time_Driver.Text = Past_Time
btn_Begin.BackColor = Color.Green
btn_Begin.Text = "Started!"
End Sub
Public Property Active_bool As Boolean
Get
Return btn_Begin.Visible
End Get
Set(ByVal value As Boolean)
btn_Begin.Visible = value
End Set
End Property
On Form1:
Private Sub btn_Start_All_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Start_All.Click
Dim allActiveUserControls = From uc_Index In Controls.OfType(Of LapTimerGUI)()
Where uc_Index.Active_bool
For Each User_Control In allActiveUserControls
User_Control.Start_Race()
Next
End Sub
I do Google my head off before I post my ridiculous questions here btw :)
This is strange. Does any MsgBoxes pop up if you add this code to your UserControl:
Private Sub UserControl_ControlRemoved(sender As Object, e As System.Windows.Forms.ControlEventArgs) Handles Me.ControlRemoved
MsgBox("Control Removed!")
End Sub
Private Sub Button2_EnabledChanged(sender As Object, e As System.EventArgs) Handles Button2.EnabledChanged
MsgBox("EnabledChanged!")
End Sub
If so, then you can add a breakpoint to these MsgBoxes and lock at the CallStack (CTRL+L) from where it triggers.
Btw: If the control is removed somehow, .PerformClick() still triggers (for me). Thus I bet, that the control is somehow disabled (Enabled = False).
Lastly, if any container of the button (such as your UserControl) is disabled, the button will be disabled too,
After lots of playing around I finally found the problem!
The value was set to =False in my properties. I'm so blonde! Thanks guys for the help ^_^/
Public Property Active_bool As Boolean
Get
Return btn_Begin.Visible
End Get
Set(ByVal value As Boolean)
btn_Begin.Visible = value
End Set
End Property
Although, Something sets the values to =False ever now and then. Very annoying :3
And I can not set the value to =True in the properties... Only in the hidden designer code...

Turn private sub into function

I have the following procedure:
Private Sub btnRptEmployeePayToMarket_MouseDown(ByValsender As Object, ByVal myButton As System.Windows.Forms.MouseEventArgs) Handles btnRptEmployeePayToMarket.MouseDown
Static Toggle As Boolean
If myButton.Button = MouseButtons.Right Then
If Toggle Then
descForm.Hide()
Else
descForm.lblReportTitle.Text = "Ranges to Market"
descForm.txtButtonDescription.Text = "Learn how you are currently paying specific departments or jobs compared to market. "
descForm.Show()
End If
End If
Toggle = Not Toggle
End Sub
Since I have about 9 buttons that will performing the same action, but only changing the text in descForm.lblReportTitle and on descForm.txtButtonDescription, how can I accomplish this?
I thought of turning the sub into a function but I am not sure how to accomplish that.
First, you need to move away from the Toggle flag so that you know when a particular button is toggled or not.
To do this, I keep a Dictionary of Boolean objects, keyed by the name of the button. When the common method is executed, it adds the flag if it does not already exist, uses it to determine the appropriate behavior, and then toggles it.
Here is a rewrite of your code with this logic in place:
Private m_cToggleFlags As New System.Collections.Generic.Dictionary(Of String, Boolean)
Private Sub btnRptEmployeePayToMarket_MouseDown(ByVal sender As Object, ByVal myButton As System.Windows.Forms.MouseEventArgs) Handles btnRptEmployeePayToMarket.MouseDown
ToggleButton(DirectCast(sender, Control).Name, "Ranges to Market", "Learn how you are currently paying specific departments or jobs compared to market.")
End Sub
Private Sub ToggleButton(sButtonName As String, sReportTitle As String, sButtonDescription As String)
If Not m_cToggleFlags.ContainsKey(sButtonName) Then
m_cToggleFlags.Add(sButtonName, False)
End If
If m_cToggleFlags(sButtonName)
descForm.Hide()
Else
descForm.lblReportTitle.Text = sReportTitle
descForm.txtButtonDescription.Text = sButtonDescription
descForm.Show()
End If
m_cToggleFlags(sButtonName) = Not m_cToggleFlags(sButtonName)
End Sub
You could add handlers to this sub.
Private Sub btnRptEmployeePayToMarket_MouseDown(ByValsender As Object, ByVal myButton As System.Windows.Forms.MouseEventArgs) Handles btnRptEmployeePayToMarket.MouseDown, btnAnotherone.MouseDown, etc...

Errorprovider shows error on using windows close button(X)

Is there any way to turn the damned error provider off when i try to close the form using the windows close button(X). It fires the validation and the user has to fill all the fields before he can close the form..this will be a usability issue because many tend to close the form using the (X) button.
i have placed a button for cancel with causes validation to false and it also fires a validation.
i found someone saying that if you use Form.Close() function validations are run...
how can i get past this annoying feature.
i have a MDI sturucture and show the form using
CreateExam.MdiParent = Me
CreateExam.Show()
on the mdi parent's menuitem click
and have this as set validation
Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If String.IsNullOrEmpty(TextBox1.Text) Then
Err.SetError(TextBox1, "required")
e.Cancel = True
End If
If TextBox1.Text.Contains("'") Then
Err.SetError(TextBox1, "Invalid Char")
e.Cancel = True
End If
End Sub
Any help is much appreciated.
googling only showed results where users were having problem using a command button as close button and that too is causing problem in my case
The ValidateChildren() method prevents the form from closing. Paste this code in your form to fix that:
protected override void OnFormClosing(FormClosingEventArgs e) {
e.Cancel = false;
}
This is quite simple fix, in your Form's Closing Event, set a flag to indicate leaving the form, for example blnLeave, when the Form gets loaded, set the flag to False, when the Closing event gets triggered, set that to True within that event handler, then the change as follows would be
Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If (blnLeave) Then
e.Cancel = False;
Return
End If
If String.IsNullOrEmpty(TextBox1.Text) Then
Err.SetError(TextBox1, "required")
e.Cancel = True
End If
If TextBox1.Text.Contains("'") Then
Err.SetError(TextBox1, "Invalid Char")
e.Cancel = True
End If
End Sub
Edit: Amended this answer for inclusion as per OP's comments. My suggestion is to handle the Form's Closed Event as shown
Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
blnLeave = True
End Sub
And handle it here in the Form's window procedure override as shown here....
Private Const SC_CLOSE As Integer = &HF060
Private Const WM_MENUSELECT As Integer = &H11F
Private Function LoWord(ByVal Num As Integer) As Integer
LoWord = Num & &HFFFF
End Function
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
If m.Msg = WM_MENUSELECT Then
If LoWord(m.WParam.ToInt32()) = SC_CLOSE Then
' Handle the closing via system Menu
blnLeave = True
End If
End If
MyBase.WndProc(m)
End Sub