Errorprovider shows error on using windows close button(X) - vb.net

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

Related

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

Highlight scroll bar of textbox [duplicate]

Is it possible to show/hide the scroll bar in a text box only when the line count in the text box is more than the number of lines displayed?
Consider using the RichTextBox -- it has that behavior built in.
Thanks dummy, it works! Here short version of dummy answer in c#
Call this code at the end of your SizeChanged and TextChanged handlers:
Size textBoxRect = TextRenderer.MeasureText(
this.YourTextBox.Text,
this.YourTextBox.Font,
new Size(this.YourTextBox.Width, int.MaxValue),
TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl);
try
{
this.YourTextBox.ScrollBars = textBoxRect.Height > this.YourTextBox.Height ?
ScrollBars.Vertical :
ScrollBars.None;
} catch (System.ComponentModel.Win32Exception)
{
// this sometimes throws a "failure to create window handle" error.
// This might happen if the TextBox is unvisible and/or
// too small to display a toolbar.
}
Public Class TextBoxScrollbarPlugin
Private WithEvents mTarget As TextBox
''' <summary>
''' After the Handle is created, mTarget.IsHandleCreated always returns
''' TRUE, even after HandleDestroyed is fired.
''' </summary>
''' <remarks></remarks>
Private mIsHandleCreated As Boolean = False
Public Sub New(item As TextBox)
mTarget = item
mIsHandleCreated = mTarget.IsHandleCreated
End Sub
Private Sub Update()
If Not mTarget.IsHandleCreated Then
Return
ElseIf Not mIsHandleCreated Then
Return
End If
Dim textBoxRect = TextRenderer.MeasureText(mTarget.Text,
mTarget.Font,
New Size(mTarget.Width, Integer.MaxValue),
TextFormatFlags.WordBreak + TextFormatFlags.TextBoxControl)
Try
If textBoxRect.Height > mTarget.Height Then
mTarget.ScrollBars = ScrollBars.Vertical
Else
mTarget.ScrollBars = ScrollBars.None
End If
Catch ex As System.ComponentModel.Win32Exception
'this sometimes throws a "failure to create window handle"
'error.
'This might happen if the TextBox is unvisible and/or
'to small to display a toolbar.
If mLog.IsWarnEnabled Then mLog.Warn("Update()", ex)
End Try
End Sub
Private Sub mTarget_HandleCreated(sender As Object, e As System.EventArgs) Handles mTarget.HandleCreated
mIsHandleCreated = True
End Sub
Private Sub mTarget_HandleDestroyed(sender As Object, e As System.EventArgs) Handles mTarget.HandleDestroyed
mIsHandleCreated = False
End Sub
Private Sub mTarget_SizeChanged(sender As Object, e As System.EventArgs) Handles mTarget.SizeChanged
Update()
End Sub
Private Sub mTarget_TextChanged(sender As Object, e As System.EventArgs) Handles mTarget.TextChanged
Update()
End Sub
End Class
Private mPlugins As New List(Of Object)
Private Sub Form_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
mPlugins.Add(New TextBoxScrollbarPlugin(txtBoxOne))
mPlugins.Add(New TextBoxScrollbarPlugin(txtBoxTwo))
mPlugins.Add(New TextBoxScrollbarPlugin(txtBoxThree))
End Sub
I've got tnimas solution working in vb. Functions quite well as written and I've not seen the errors.
Private Sub TextBoxSizeChanged(sender As Object, e As EventArgs) Handles Me.SizeChanged
Dim textBoxRect As Size = TextRenderer.MeasureText(TextBox.Text, TextBox.Font, New Size(TextBox.Width, Integer.MaxValue), TextFormatFlags.WordBreak Or TextFormatFlags.TextBoxControl)
Try
TextBox.ScrollBar = If(textBoxRect.Height > TextBox.Height, ScrollBars.Vertical, ScrollBars.None)
Catch ex As Exception
'handle error
End Try
End Sub
I myself tried tnimas' solution but unable to catch the exception, so I use the WinApi to toggle the visible state of scrollbars instead like so:
Size textBoxRect = TextRenderer.MeasureText(YourTextBox.Text, YourTextBox.Font, new Size(YourTextBox.Width, int.MaxValue), TextFormatFlags.WordBreak | TextFormatFlags.TextBoxControl);
WinApi.ShowScrollBar(YourTextBox.Handle, (int)WinApi.ScrollBar.SB_VERT, textBoxRect.Height > YourTextBox.Height ? true : false);
This method does not cause the exception, though should note that hiding scrollbars like this will disable scroll messages, but this is fine if you're just hiding the scrollbars for when the text area can't be scrolled anyway.

Tabindex ignored when Enabled set to true in a validating event handler

I have three text boxes.
txtBox1 - Enabled=True - TabIndex=1
txtBox2 - Enabled=False - TabIndex=2
txtBox3 - Enabled=True - TabIndex=3
I have an event handler that sets Enabled=True for txtBox2 when txtBox1 is validating. My problem is that the cursor doesn't go to txtBox2 after leaving txtBox1, it jumps to txtBox3.
Private Sub Example(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) Handles txtBox1.Validating
txtBox2.Enabled = True
End Sub
Is there a way to have the TabIndex respected after a field is enabled in a validating event handler? I can use Select() but that breaks reverse tabbing through the fields (SHIFT+TAB).
Thank you!
It is a simple chicken-and-egg problem. The Validating event fires because the textbox lost the focus. Which happened because you tabbed to the next control. Which was of course txtBox3, enabling txtBox2 does not change that.
Easy to fix, the ActiveControl property tells you which control is active. So write it like this:
txtBox2.Enabled = True
If Me.ActiveControl Is txtBox3 Then txtBox2.Focus()
Back-tabbing works properly as long as you have more than 3 controls that can receive the focus.
Ok so I posted the wrong solution so here is the correct one. Hans got me thinking and this is what I came up with that works for my needs:
Public Class Form1
' First you have to declare a variable
Dim m_TabForward As Boolean
' Capture the keystrokes to check for direction.
Private Sub GetTabDirection(ByVal sender As Object, _
ByVal e As PreviewKeyDownEventArgs) Handles _
txtBox1.PreviewKeyDown
If (e.KeyCode = Keys.Tab AndAlso e.Modifiers = Keys.Shift) Then
m_TabForward = False
ElseIf e.KeyCode = Keys.Tab Then
m_TabForward = True
End If
End Sub
' Enable the next textbox and select it. Because SelectNextControl
' takes a direction argument you don't have a problem with reversing order
' like you would using txtBox2.Select()
Private Sub ValidateFields(ByVal Sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles txtBox1.Validating
Dim ctl As Control = Sender
If Sender Is txtBox1 Then
txtBox2.Enabled = True
End If
SelectNextControl(ctl, m_TabForward, True, True, True)
End Sub
End Class

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...

Disabling checkbox selections in VB .NET 2008 Winform Listview

How do you disable additional checkbox selections/deselections without sacrificing the functionality of the ListView? I know you can call: ListView.Enabled = False, but that also disables any scrolling within it.
For example: I have a timer that starts a backup based on the Listview items that are checked. After a certain time, I don't want the end-user to be able to click on any of the checkboxes within the listview (so I have a set number of items to backup), but I do want them to be able to scroll the list while the backup is being performed. I tried this:
Private Sub clboxOptions_ItemChecked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ItemCheckedEventArgs) Handles clboxOptions.ItemChecked
If backupStarted = True Then
If e.Item.Checked = True Then
e.Item.Checked = False
Else
e.Item.Checked = True
End If
But this doesn't seem to work for me.
Thanks!
JFV
Here is an other method to disable the users click on listviewitem checkbox.
Public Sub ChangeItemCheckState(ByVal val As Boolean, ByVal index As Integer)
If Monitor.TryEnter(Me.Items(index), 10) Then
Try
Me.Items(index).Checked = val
Finally
Monitor.Exit(Me.Items(index))
End Try
End If
End Sub
Public Sub ChangeItemCheckState(ByVal val As Boolean, ByVal item As ListViewItem)
If Monitor.TryEnter(item, 10) Then
Try
item.Checked = val
Finally
Monitor.Exit(item)
End Try
End If
End Sub
Private Sub ListviewOPC_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles Me.ItemCheck
If Monitor.IsEntered(Me.Items(e.Index)) Then
'
Else
'prevent click from users
e.NewValue = e.CurrentValue
End If
End Sub
this method is thread safe. To change the checkedstate of an item you have to call the ChangeItemCheckState methods. If you want to enable/disable the itemcheck by click, you have to add another property.
Private disableUserCheckItem As Boolean
Public Property PreventUserCheckItem() As Boolean
Get
Return disableUserCheckItem
End Get
Set(ByVal value As Boolean)
disableUserCheckItem = value
End Set
End Property
Public Sub ChangeItemCheckState(ByVal val As Boolean, ByVal index As Integer)
If Monitor.TryEnter(Me.Items(index), 10) Then
Try
Me.Items(index).Checked = val
Finally
Monitor.Exit(Me.Items(index))
End Try
End If
End Sub
Public Sub ChangeItemCheckState(ByVal val As Boolean, ByVal item As ListViewItem)
If Monitor.TryEnter(item, 10) Then
Try
item.Checked = val
Finally
Monitor.Exit(item)
End Try
End If
End Sub
Private Sub ListviewOPC_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles Me.ItemCheck
If Monitor.IsEntered(Me.Items(e.Index)) Then
'do nothing or other nessesary things.
Else
'prevent click from users
If PreventUserCheckItem Then
e.NewValue = e.CurrentValue
End If
End If
End Sub
Instead using the built-in CheckBoxes property, you could draw the check boxes yourself.
Google around and find an example of an OwnerDraw ListView. Draw the checkboxes yourself. Add a new property to your ListView (something like ReadOnly). When ReadOnly is true, draw the checkboxes as disabled and ignore the click messages.
You could use ObjectListView (which is a wrapper around a normal .NET ListView). It provides a callback, CheckStatePutter, which is called when the user clicks on a checkbox. In that callback, you can decide whether or not to accept the new checkbox value.
This is a recipe describing this process: How do I use checkboxes in my ObjectListView?
I found out what my issue was. I was using the 'ItemChecked' instead of the 'ItemCheck' Method. The below code works for me:
Private Sub clboxOptions_ItemCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ItemCheckEventArgs) Handles clboxOptions.ItemCheck
Try
If backupStarted = True Then
If e.CurrentValue <> e.NewValue Then
e.NewValue = e.CurrentValue
Else
e.NewValue = e.NewValue
End If
End If
End Sub
I want disable CheckBox in Listview. When I click Button Go. I was using the 'ItemChecked' Method. I use code this:
Public Sub CheckBoxChecked(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckedEventArgs)
Try
If bCheckFromEvent Then
bCheckFromEvent = False
Return
End If
If BrunService Then
bCheckFromEvent = True
ListView.Items(e.Item.Index).Checked = Not ListView.Items(e.Item.Index).Checked
End If
Catch ex As Exception
MsgBox("CheckBoxChecked: " & ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly, "ERROR")
End Try
End Sub