Closing a Windows Form, using the Close Window button, when a Validation Message is showing - winforms

I have a Windows form that has a validation event on a textBox so that if the value of that TextBox is a value that already exists it triggers a validation error.
private void txtUsername_Validating(object sender, CancelEventArgs e)
{
var alreadyExists = _logic.UserIdExists(txtUsername.Text.Trim());
if(alreadyExists)
{
errorProvider1.SetError(txtUsername, "This Userid already exists, please choose an alternative");
e.Cancel = true;
}
}
private void txtUsername_Validated(object sender, EventArgs e)
{
errorProvider1.SetError(txtUsername, "");
}
this.txtUsername.Validating += new System.ComponentModel.CancelEventHandler(this.txtUsername_Validating);
this.txtUsername.Validated += new System.EventHandler(this.txtUsername_Validated);
This results in an error image appearing next to that textBox along with a tooltip error message.
If I try and close the application, using the Close button at the top of the window, at this time I cannot as the above Event keeps firing even when I try and close the window (due to me taking focus away from the Text box).
Is there a way of closing the window, without resorting to creating an additional Close button on the form?

Based on your description, you want to maintain the default auto-validation behavior yet allow the Form to be closed using the title bar close button. I have observed that the Form.Closing event is raised in such a circumstance, however its argument Cancel property is preset to true. A simple solution is to handle this event and set e.Cancel = false. Implement any logic in the handler that you deem necessary.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing) e.Cancel = false;
}

Related

Winforms ContextMenuStrip wont open when Opening event is handled

I'm moving a Winforms app from VB to C#. I have a TrueDBGrid with a ContextMenuStrip thats pops up on a right click. When I don't handle the mnuContext Opening event the menu pops up. When I do handle the event the handler is called but the menu wont popup - even if the handler does nothing.
The code below has been trimmed to just have the handler call, so it's not what the code is doing, just the existence of the handler itself.
public void MenuOpeningHandler(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = false;
}
Setup code is:
public InvoiceListForm()
{
InitializeComponent();
mnuContext.Opening += MnuContext_Opening;
}
private void MnuContext_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
MenuOpeningHandler(sender, e);
e.Cancel = false;
}
The event appears to be stopped/Cancelled instead of continuing to propagate and open. Any idea what could be missing?

WinForms form partially loses focus after disabling all controls

The focus rectangle and textbox caret are lost after disabling all controls, then enabling them again (vs2012 / .NET Framework v4.5).
To reproduce the issue, just create a WinForms application project, add a button and a textbox in the form, then use this code to disable and enable both controls in the button click event:
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
textBox1.Enabled = false;
button1.Enabled = true;
textBox1.Enabled = true;
}
You may cycle between the textbox and the button using Tab/Shift+Tab as expected, until you press the button.
After that, the focus is partially lost (its weird). You can still use Tab/Shift+Tab and arrows to nagivate between the controls, and press Enter to active the button, but you cannot type in the textbox, nor use the space key to press the button. The textbox caret and the button focus rectangle are not displayed anymore. Changing focus to another application then returning to this form will fix the focus issue.
This issue does not happen if you don't disabled at least one control that is able to receive focus. Also the focus behavior is restored by disabling and enabling again the form, like this:
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
textBox1.Enabled = false;
button1.Enabled = true;
textBox1.Enabled = true;
this.Enabled = false;
this.Enabled = true;
}
I was trying to disable all the controls of a more complex form at the start of a task, so the task would enable again all controls after finishing, to prevent user input during the processing, but without locking the UI thread. I thought it was related to the cross-thread invoke calls, but I found this issue happens even with all code running on UI thread.
This undesired behavior can be fixed by calling the form Focus() method:
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
textBox1.Enabled = false;
button1.Enabled = true;
textBox1.Enabled = true;
this.Focus();
}
The ActiveControl is not changed after calling Focus(), so this works very well for me.

Windows.Activated in wpf fires multiple times

Hi I have a code to be written while window(WPF window) activate like clicking on the window or using alt/tab. The window is the child of a main form (windows app). I have used ToolWindow as the windowstyle.
It has a xamdatagrid which has to updated on activation
Problem is it fires multiple times. It should be fired once. I don not want my code to run multiple times
How to make it work. please help
From the Window.Activated Event page on MSDN:
Occurs when a window becomes the foreground window.
The Window.Activated Event is supposed to be called multiple times, so perhaps it is not the best event for you to handle. Alternatively, you could add a bool isFirstTime variable and use it to restrict your code to only being called once. Take this example:
private bool isFirstTime = true;
...
private void WindowActivated(object sender, EventArgs e)
{
if (isFirstTime)
{
isFirstTime = false;
// do something here just once
}
}
However, as (from the linked page)...
A window is activated (becomes the foreground window) when:
• The window is first opened.
• A user switches to a window by selecting it with the mouse, pressing ALT+TAB, or from Task Manager.
• A user clicks the window's taskbar button.
... you may find that this will not work for you.
I got it done.
I was using the below code
private void OnAttributeHistoryWindowActivated(object sender, EventArgs e)
{
var win = ((RoutedEventArgs)(e)).Source as AttributeHistoryWindow;
//My Code
}
The first line of code was firing back the Activated event. And it never goes to the next line of my code.
Now I used below code and it works.
private void OnAttributeHistoryWindowActivated(object sender, EventArgs e)
{
var win = sender as AttributeHistoryWindow;
//My Code
}
Now it fires once.

How to handle exception from underlying dataset of an Ultrawingrid (winforms)

I have an UltraWinGrid with a dataset behind it. In the datatable's Row_Changing event handler, I do some checking of the data and throw an exception if it is invalid. I want to display a message for this exception within my application. However, the UltraGrid seems to catch the exception and display it's own message box with the exception. How can I prevent the message box from being displayed, and catch that error within my application?
private static void Row_Changing( object sender, DataRowChangeEventArgs e )
{
if( <some logic to test the row values>)
throw new Exception("you can't do that");
}
I worked it out, but I thought I'd create this question anyway (since I have already typed it out).
You need to handle the Error event of the UltraGrid and set e.Cancel to true to prevent the dialog box from popping up:
public Form1()
{
...
this.ultraGrid1.Error += new Infragistics.Win.UltraWinGrid.ErrorEventHandler(ultraGrid1_Error);
}
void ultraGrid1_Error(object sender, Infragistics.Win.UltraWinGrid.ErrorEventArgs e)
{
//< deal with the error here>
// set Cancel to true to prevent the dialog box from showing.
e.Cancel = true;
}

How do prevent a WPF text box inside a combo from reacting to right mouse clicks?

I creating a custonmized box class (inherits from ComboBox). I don't want the text box to react to right mouse clicks. I can get rid of the context menu by setting this to null in ApplyTemplate, but right mouse clicks move the cursor. I tried hooking up PreviewMouseRightButtonDown in ApplyTemplate and setting Handled to True, but the event still gets through which is strange as it seems to work for the left click.
The cursor actually moves when the mouse button is released, so you want mark the MouseRightButtonUp event as handled. You could override OnMouseRightButtonUp:
protected override void OnMouseRightButtonUp(MouseButtonEventArgs e)
{
base.OnMouseRightButtonUp(e);
e.Handled = true;
}
Or you could attach a class handler to the MouseRightButtonUp event to mark it as handled:
static MyComboBox()
{
EventManager.RegisterClassHandler(
typeof(MyComboBox),
MouseRightButtonUpEvent,
new MouseButtonEventHandler(MyComboBox_MouseRightButtonUp));
}
private static void MyComboBox_MouseRightButtonUp(
object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
That will also prevent the context menu from being created without you having to set it to null explicitly.

Resources