Have to Click Form To Give Focus - vb.net

I have a main form with buttons that open a custom message box form. It works fine if it's just a message and the user just needs to click OK. But if the answer to that message box is important, like "Are you sure you want to delete this file?" I use a while loop to wait for the user to respond and once they do then a flag is set from false to true and the response is recorded.
For some reason any response that uses a while loop to wait is causing the message box form to not have focus after being called. Requiring the user to first click on the form, and then click on OK.
So far I've tried using form.Activate() instead of form.Show(), as well as calling Application.DoEvents() inside the while loop since I believed the while loop was taking focus away from the message form immediately after being called. Neither solved the issue.
Code from a message box that works as intended:
If cmbLoadProgram.SelectedItem = "" Then
frmMessageBox.lblHeader.Text = "Set-Up"
frmMessageBox.lblMessageText.Text = "No Program Selected!"
frmMessageBox.Show()
Exit Sub
End If
Code from a message box that needs to be clicked twice:
If btnGetHexStart.Visible = False And cmbStartCondition.SelectedItem = "Pixel" Then
frmMessageBox.lblHeader.Text = "Hex Set-Up"
frmMessageBox.lblMessageText.Text = "Reset Hex Code Data?"
frmMessageBox.Show()
Me.Hide()
While Flag = False
If frmMain.OKCancel = "OK" Then
btnGetHexStart.Visible = True
btnGetHexStart.Enabled = True
btnGetHexStart.PerformClick()
Flag = True
End If
frmMain.delay(20)
End While
End If
I'm wanting both options to only need to be clicked once in order to confirm or cancel the action. Instead of the while loop questions needing to be clicked twice.

This just an idea from me, just how to open msgboxform, here we need MessageForm and one module1, for example:
Public Class MessageForm
'You can assign any variable to show any data in messageform display
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
theResult = MsgBoxResult.Ok
Me.Close()
Me.Dispose()
End Sub
Private Sub bttcancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttcancel.Click
theResult = MsgBoxResult.Cancel
Me.Close()
Me.Dispose()
End Sub
End Class
Module Module1
Public theResult As MsgBoxResult
'You can add some parameter here to submit to MessageForm
Public Function myMessageBox() As MsgBoxResult
myMessageBox = MsgBoxResult.Cancel
MessageForm.ShowDialog()
myMessageBox = theResult
End Function
End Module
and then you can call the myMessageBox anywhere like this:
'if myMessageBox procedure have parameter, apply the paramters too
dim myRslt = myMessageBox()

You don't need to create a form,You can use DialogResult and MessageBox.Show, code:
Dim Result As DialogResult = MessageBox.Show("Set-Up" & vbCrLf & "No Program Selected!", "Warning", MessageBoxButtons.OKCancel)
If Result = DialogResult.OK Then
ElseIf Result = DialogResult.Cancel Then
End If

Related

Custom InputBox Not Recording Response

I have created a custom InputBox using frmInputBox.ShowDialog and using 2 buttons titled "OK" and 'Cancel", with them set to the AcceptButton & CancelButton respectively. This is simply so I can have the InputBox match the formatting of my main Form. However when I enter a value into the TextBox on frmInputBox the form doesn't disappear and my code gets hung up with the InputBox still open.
I tested my code using a custom MessageBox and with all the same options it works perfectly fine. The issue with the InputBox must have something to do with the TextBox not being recorded properly. But I don't see any options in the TextBox control to set it up as a Dialog option.
Here's sample code for my MessageBox:
frmMessageBox.lblMessageText.Text = "Would You Like To Clear The Event Log?"
frmMessageBox.ShowDialog()
If frmMessageBox.DialogResult = DialogResult.OK Then
txtEventLog.Clear()
Else
Exit Sub
End If
Here's sample code for my InputBox:
frmInputBox.lblDialogText.Text = "Enter Number of times this program should be executed:"
frmInputBox.ShowDialog()
If frmInputBox.DialogResult = DialogResult.OK Then
ProgramCounter = frmInputBox.txtDialogInput.Text
Else
Exit Sub
End If
Is there something I'm missing that I need to do with the InputBox in order to get it to act the way I am expecting it to?
For messagebox, I have answer before, and for inputbox, same as messagebox you need a module1:
Module Module1
Public theResult As String
Public Function myInputBox(ByVal promptText As String) As String
InputBoxForm.lblPrompt.Text = promptText
InputBoxForm.ShowDialog()
myInputBox = theResult
End Function
end Module
You need inputbox form:
Public Class InputBoxForm
Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
theResult = txtInputResponse.Text
Me.Close()
Me.Dispose()
End Sub
Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
theResult = ""
Me.Close()
Me.Dispose()
End Sub
End Class
And then you can call your input box like this:
Dim theRslt as String = myInputBox("Enter Number of times this program should be executed:")
MsgBox(theRslt)

Message box on close only show when text is changed

So I take no credit to the following code as it was given to me by another fellow user and don't get me wrong it works great but now I only Want the message box to show when text is changed in textboxes and if all text boxes are empty to just close the app when the X is clicked.
Any help is appreciated!
'Creates _handle as boolean
Private _handle As Boolean = True
Private Sub MainWindow_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
'Creates a messagebox to ask if the user wants to exit the application or no. If yes application closes, if no then application stays open
If _handle = True Then
e.Cancel = True
Dim result = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.YesNo, MessageBoxImage.Question)
If (result = MessageBoxResult.Yes) Then
_handle = False
Environment.Exit(0)
End If
End If
End Sub

VB.NET: DialogResult.No is not closing the form

Using Message Box DialogResult.No Condition for closing the form doesnot perform as expected.
The formclosing event aske user whether to save the document or not before closing.
The following is my FormClosing event.
Private Sub PDFViewSimple_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) _
Handles Me.FormClosing
If doc.IsModified Then
Dim message As String = "The document is modified, would you like to save it?"
Dim caption As String = "File Not Saved"
Dim buttons As MessageBoxButtons = MessageBoxButtons.YesNo
Dim DefaultButton As MessageBoxDefaultButton = MessageBoxDefaultButton.Button1
Dim icon As MessageBoxIcon = MessageBoxIcon.Question
Dim result As DialogResult
' Displays A MessageBox.
result = MessageBox.Show(message, caption, buttons, icon, DefaultButton)
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
Me.Close()
ElseIf (result = DialogResult.No) Then
Me.Close() ''Should I replace with (Application.Exit)
End If
End If
End Sub
There's all sorts wrong with that code. Firstly, given that there are only two options, using ElseIf is pointless, although not strictly wrong. If it's not Yes then it must be No, so you'd only need an Else:
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
Me.Close()
Else
Me.Close()
End If
Next, even an Else is pointless because you're calling Close regardless of the outcome. All you need to do is check for Yes, do anything specific to Yes and then call Close regardless:
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
End If
Me.Close()
Finally, you shouldn't be calling Close at all. You're in the FormClosing event handler so the form is already closing. You only have to do something if you want the form to NOT close. So, all you need is this:
If (result = DialogResult.Yes) Then
Me.Save(Me.Text)
End If
If you wanted the form to NOT close then you would set e.Cancel to True.

Can't get checking if file exists using textboxes to work

I've been racking my brain for days over this code and I just can't seem to get it working. I've researched and researched with no luck. I have four textboxes on my form. Two textboxes is a folder location and the other two textboxes are file locations. I'm trying to use a function that will return true or false telling if the files in the two textboxes exist or not. I don't see anything at all wrong with this code and it just won't work! I'm sure it's something simple I'm overlooking. Maybe someone else can spot it!
Private Function doesFileExist(folderPath, fileName) As Boolean
If IO.File.Exists(folderPath & "\" & fileName) Then
Return True
Else
Return False
End If
End Function
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If doesFileExist(txtCPU.Text, txtFileCPU.Text) And
doesFileExist(txtGPU.Text, txtFileGPU.Text) Then
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
Else
chkStart.Checked = False
chkStart.Text = "Start Monitor"
End If
Else
chkStart.Checked = False
MessageBox.Show("Please check directory & file locations!", "Error!", MessageBoxButtons.OK)
End if
End Sub
I want to mention that before I tried nested if statements on this I also tried to separate them both like so..
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If Not doesFileExist(txtCPU.Text, txtFileCPU.Text) And
Not doesFileExist(txtGPU.Text, txtFileGPU.Text) Then
chkStart.Checked = False
MessageBox.Show("Please check directory & file locations!", "Error!", MessageBoxButtons.OK)
Exit Sub
End If
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
Else
chkStart.Checked = False
chkStart.Text = "Start Monitor"
End If
End Sub
Both of these ways will show the messagebox if the application is ran with the checkbox checked on start up. Not only will it show the messagebox it also shows the messagebox twice! I've yet to figure that one out!
Your check file exists can be simplified... (It's been a while since I used VB so apologies for any syntax errors, I don't have an IDE to hand)
Function DoesFileExist(Folder as String, Filename As String) As Boolean
Return IO.File.Exists(IO.Path.Combine(Folder, Filename))
End Function
Re: Changing whether the "check" checkbox is set shouldn't perform the check itself - otherwise you only check when people click. (Incidentally, I'm guessing you're getting a message twice as code elsewhere ticks/unticks this checkbox, but it's only a guess).
Private Sub chkStart_CheckedChanged(sender As Object, e As EventArgs) Handles chkStart.CheckedChanged
If chkStart.Checked Then
chkStart.Text = "Stop Monitor"
PollTimer.Start()
Else
chkStart.Text = "Start Monitor"
PollTimer.Stop()
End if
End Sub
Finally... You need to define when your check will happen. Ideally, you'd want to use a FileSystemWatcher which will give you events when the file system changes, but you can also poll using a timer...
Private PollTimer As System.Timers.Timer
Then in your Form Main, do some initial timer setup...
...
PollTimer = New System.Timers.Timer()
PollTimer.Interval = 30000 ' Seconds
AddHandler PollTimer.Elapsed, AddressOf CheckExistsNow
PollTimer.Start()
...
And finally the code to run every time we want to make the check....
Sub CheckExistsNow(sender As Object, e As System.Timers.ElapsedEventArgs)
If Not DoesFileExist(txtGPU.Text, txtFileGPU.Text) Then
' Handle the missing file.
End if
End Sub

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