WPF Detecting Window Close Event and coupling with a button event - c#

For two days, I have tried various methods for making it so that on loadButton click, it opens a secondary window and disables the loadButton; Then, when that secondary window has been closed, the loadButton will be re-enabled. Although, obviously all of my attempts have been unsucessful.
I have been reading about using the isClosing event, although, I haven't figured out how to properly implement it. So I decided to go with this route.
private void loadButton_Click(object sender, RoutedEventArgs e)
{
var richWindow = RichTextWindow.GetWindow(new RichTextWindow());
if (richWindow.IsActive != true)
{
loadButton.IsEnabled = false;
richWindow.Show();
}
else
{
loadButton.IsEnabled = true;
}
}
Issue here is, the first half is executed. Once I click the loadButton, it does disable. However, on closing the new Window, the loadButton is still disabled.
Could anyone point me in the right direction on where I need to go with this?

I think what you want is something like this:
private void loadButton_Click(object sender, RoutedEventArgs e)
{
var richWindow = RichTextWindow.GetWindow(new RichTextWindow());
richWindow.Closed += (s, e) => loadButton.IsEnabled = true;
loadButton.IsEnabled = false;
richWindow.Show();
}
Basically, disable the button before opening the window. Then, listen for the window to close and enable the button again.

richWindow.Loaded +=
{
loadedButton.IsEnabled = false;
};
richWindow.Closing +=
{
loadedButton.IsEnabled = true;
}

Related

c# mainui drops behind other windows, issue with topmost

I have a problem with topmost level, found a solution that "works" but it don't look so nice. Is there another "cleaner" way to solve this?
Here's my code: comments of event in code.
OrderTemplateView template;
private void toolStripButton4_Click(object sender, EventArgs e)
{
if (template != null)
{
template.Close(); //must close to trigger close event.
template.Dispose();
}
mainUi.TopMost = true; // must set my mainUi topMost here othervise it drops in the background of other windows open at the computer.
template = new OrderTemplateView(this);
template.TopMost = true;// must set my dialog topmost othervise it drops behind my mainUi
template.StartPosition = FormStartPosition.CenterParent;
mainUi.TopMost = false;//must release my topmost so other windows on the computer can be called to front.
template.TopMost = false;
template.ShowDialog();
}
Updated code that does the same job:
private void toolStripButton4_Click(object sender, EventArgs e)
{
if (template != null)
{
template.Close();
template.Dispose();
}
template = new OrderTemplateView(mainUi);
template.StartPosition = FormStartPosition.CenterParent;
template.ShowDialog(mainUi);
}
`
Rather than setting TopMost, try the following:
Remove all your references to TopMost
Call mainUi.BringToFront()
Call template.ShowDialog(mainUi), noting that the parent control is passed to the dialog.

Button clicked once

I have a problem with the option to select the button once when it is open, what am I doing wrong?
private Boolean buttonWasClicked = false;
private void Button_Click(object sender, RoutedEventArgs e)
{
buttonWasClicked = true;
if ( buttonWasClicked == true)
{
new SettingsWindow().Show();
var test = new SettingsWindow();
test.Owner = System.Windows.Application.Current.MainWindow;
test.WindowStartupLocation = WindowStartupLocation.CenterOwner;
test.Top = this.Top + 20;
}
else {
buttonWasClicked = false;
}
}`
I would avoid to keep your own flag variable and manage its setting by hand. For example, if the user closes the window how do you change back the variable to allow again opening a SettingsWindow?. There is a more robust system based approach at this problem. Looking at system provided informations will help you to avoid opening a second time the settings window until there is already one instance opened.
To check if there is already an instance of a SettingsWindow open you could use informations provided by the system with code like this
private void Button_Click(object sender, RoutedEventArgs e)
{
// Check if, in the Application.Current.Windows collection
// there is at least one window of type SettingsWindow
SettingsWindow w = Application.Current.Windows
.OfType<SettingsWindow>()
.FirstOrDefault();
if(w == null)
{
// No window of the type required, open a new one....
w = new SettingsWindow();
w.Owner = System.Windows.Application.Current.MainWindow;
w.WindowStartupLocation = WindowStartupLocation.CenterOwner;
w.Top = this.Top + 20;
}
// Show it NON MODALLY....
w.Show();
}
The call to Show returns immediately (Non modally) and thus your program continue as usual with the MainWindow still active.
Instead, if you want to use a modal approach, (meaning that until the SettingsWindow is open nothing in your MainWindow is active) you could simply create the SettingsWindow, set its Owner and eventually its Position and finally call ShowDialog (Do not forget to set the Owner property). In this way your code is blocked in the ShowDialog and doesn't return until the user closes the SettingsWindow instance just opened. (And you could remove all the checking above)
Pretty sure this will always be true
Go with the excellent answer from Steve
buttonWasClicked = true;
if (buttonWasClicked == true)
{
// this will execute every time
}
else
{
// this will never execute
}

XAML enable/disable view from another view

I'm a beginner and having some dicciculties with XAML.
I have a main view A, which has a button to open a pop-up-window B. When this happens, Window A should still be visible and openened, but disabled. I've done this in code behind (maybe not the cleanest way, but the only way I know how). The code i used for this is the following:
//Code behind from view A
private void X-Button_Click(object sender, RoutedEventArgs e)
{
var BWindow = new BView();
BWindow.Show();
this.IsEnabled = false;
}
I would like to get window A enabled again once i close window B, but i can t seem to get this work. Any help would be very much appreciated.
You could do it in the following way.
You register yourself on the Closed event of the window, and when it gets closed, you unregister the event, and re-enable the this form.
private void Button_Click(object sender, RoutedEventArgs e)
{
Window BWindow = new BWindow();
BWindow.Show();
BWindow.Closed += BWindow_Closed;
this.IsEnabled = false;
}
void BWindow_Closed(object sender, EventArgs e)
{
Window win = sender as Window;
if (win != null)
{
win.Closed -= BWindow_Closed;
}
this.IsEnabled = true;
}
I assume you are looking for modal window. See similar question asked here: How do make modal dialog in WPF?
The solution is in using ShowDialog method from Window class. See here for reference:
http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog.aspx
Modal window is the concept when you open new window B from the existing window A. While the B is open, the A is disabled and cannot be used. Window A become active only when the B is closed.

Trouble with POPUP and Events in Windows Phone 7.1

I have a button that activate a service but before that service is activate i need to force the user to enter a text, for that task i create a user control that allow the user to enter text and validate it, on that control i have 2 buttons OK and cancel, OK button is working fine but the cancel is supposed to hide the popup, but the event don't get triggered, i need to hit the button several times before that happen, i am also getting a similar problem if the person hits back i cant get rid of the popup without closing the app. What is the best approach to work with popup and in this case why is the event is not getting trigger on the first hit
public partial class TicketView
{
Controls.TextInputBox textInputControl;
private void InitCloseTxtInput()
{
textInputControl = new Controls.TextInputBox(8, 0);
textInputControl.CancelBtn.Click += new RoutedEventHandler(CancelBtn_Click);
textInputControlForCamara.CancelBtn.Click += new RoutedEventHandler(CancelBtn_Click);
}
private void AppBarBtn_Click(object sender, EventArgs e)
{
InitCloseTxtInput();
PivotContainer.IsEnabled = false;
this.popup = new Popup();
this.popup.Margin = new Thickness(0, 150, 0, 0);
this.popup.Child = textInputControl;
this.popup.IsOpen = true;
}
void OkBtnOnPopUP_Click(object sender, RoutedEventArgs e)
{
//Call Service
}
void CancelBtn_Click(object sender, RoutedEventArgs e)
{
this.popup.IsOpen = false;
this.PivotContainer.IsEnabled = true;
}
}
If anyone have any out of question recommendation for this piece of code, Please tell me.
This line was the problem don’t exactly know why but when trying to re do de control i comment this line and all start to work just fine
this.popup.Margin = new Thickness(0, 150, 0, 0);
At least in the code, it does not seem like you are hooking CancelBtnPopUP_Click anywhere.
Is that the entirety of the code?

Preventing a dialog from closing in the button's click event handler

I have a dialog that I show with <class>.ShowDialog(). It has an OK button and a Cancel button; the OK button also has an event handler.
I want to do some input validation in the event handler and, if it fails, notify the user with a message box and prevent the dialog from closing. I don't know how to do the last part (preventing the close).
You can cancel closing by setting the Form's DialogResult to DialogResult.None.
An example where button1 is the AcceptButton:
private void button1_Click(object sender, EventArgs e) {
if (!validate())
this.DialogResult = DialogResult.None;
}
When the user clicks button1 and the validate method returns false, the form will not be closed.
Given that you've specified you want a pop error dialog, one way of doing this is to move your validation into a OnClosing event handler. In this example the form close is a aborted if the user answers yes to the question in the dialog.
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}
By setting e.Cancel = true you will prevent the form from closing.
However, it would be a better design/user experience to display the validation errors inline (via highlighting the offending fields in some way, displaying tooltips, etc.) and prevent the user from selecting the OK button in the first place.
Don't use the FormClosing event for this, you'll want to allow the user to dismiss the dialog with either Cancel or clicking the X. Simply implement the OK button's Click event handler and don't close until you are happy:
private void btnOk_Click(object sender, EventArgs e) {
if (ValidateControls())
this.DialogResult = DialogResult.OK;
}
Where "ValidateControls" is your validation logic. Return false if there's something wrong.
You can catch FormClosing an there force the form to remain opened.
use the Cancel property of the event argument object for that.
e.Cancel = true;
and it should stop your form from closing.
This doesn't directly answer your question (other already have), but from a usability point of view, I would prefer the offending button be disabled while the input is not valid.
Use this code:
private void btnOk_Click(object sender, EventArgs e) {
if (ValidateControls())
this.DialogResult = DialogResult.OK;
}
The problem of it is that the user has to clic two times the buttons for closing the forms;
Just add one line in the event function
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
this->DialogResult = System::Windows::Forms::DialogResult::None;
}
I wish I had time to find a better example, but you would be much better off using the existing windows forms validation techniques to do this.
http://msdn.microsoft.com/en-us/library/ms229603.aspx
void SaveInfo()
{
blnCanCloseForm = false;
Vosol[] vs = getAdd2DBVosol();
if (DGError.RowCount > 0)
return;
Thread myThread = new Thread(() =>
{
this.Invoke((MethodInvoker)delegate {
picLoad.Visible = true;
lblProcces.Text = "Saving ...";
});
int intError = setAdd2DBVsosol(vs);
Action action = (() =>
{
if (intError > 0)
{
objVosolError = objVosolError.Where(c => c != null).ToArray();
DGError.DataSource = objVosolError;// dtErrorDup.DefaultView;
DGError.Refresh();
DGError.Show();
lblMSG.Text = "Check Errors...";
}
else
{
MessageBox.Show("Saved All Records...");
blnCanCloseForm = true;
this.DialogResult = DialogResult.OK;
this.Close();
}
});
this.Invoke((MethodInvoker)delegate {
picLoad.Visible = false;
lblProcces.Text = "";
});
this.BeginInvoke(action);
});
myThread.Start();
}
void frmExcellImportInfo_FormClosing(object s, FormClosingEventArgs e)
{
if (!blnCanCloseForm)
e.Cancel = true;
}
You can probably check the form before the users hits the OK button. If that's not an option, then open a message box saying something is wrong and re-open the form with the previous state.

Categories

Resources