this.Close() won't work - winforms

I have a windows forms app (c# 4.0) and the "X" button won't close the form, and this.close() won't do it either.
Other forms work fine, yet when I copy the designer over to a new form, it breaks that form too!
any clues?

so... apparently this makes it work (creating a closing event, and putting in the following code)
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.Dispose();
}

Related

Hide cursor wpf WebBrowser control?

neither
<WebBrowser x:Name="wbMain" Cursor="None"></WebBrowser>
nor
*{cursor:none}
is working for me. I can't find any resources online telling me how to accomplish this. The use-case for this is an application that runs full screen meant for viewing only after the setup takes place.
Edit: I forgot to add that the css works as expected when viewing the website in the IE9 browser.
I don't know if this is a good or bad practice but you can add System.Windows.Forms reference
then
private void MouseEnter(object sender, MouseEventArgs e)
{
System.Windows.Forms.Cursor.Hide();
}
private void MouseLeave(object sender, MouseEventArgs e)
{
System.Windows.Forms.Cursor.Show();
}
use this code on mouseEnter form example in web-browser control
For those who dont like to add WinForms reference, try
[DllImport("user32.dll")]
static extern int ShowCursor(bool bShow);
and call ShowCursor(false) when needed.
In app.cs
protected override void OnStartup(StartupEventArgs e)
{
System.Windows.Forms.Cursor.Hide();
}

Windows Close button in WPF

I am currently working on a WPF application with Caliburn framework. At the top right of the application windows, there is a windows CLOSE(X) button. I would like to catch the event for the windows CLOSE button. However, when the application window is closing, the fade out will begin regardless of any buttons which will close the application windows. Also, when the application closes, the application will ask the user whether they want to save the changes or not if there is any changes. However, I can only manage to get the EXIT button in my application to pop up the SAVE CHANGES message and then start the fade out, but this does not occur for the windows CLOSE(X) button. When I pressed the windows CLOSE(X) button, the fadeout will begin first*(Therotically, this shouldn't happen, it should show the SAVE CHANGES message first and then fadeout afterwards)*. During the fade out, the SAVE CHANGES message appears. At the end, the application crashes because the application cannot close as the message still shows in the application. Does any one know any way to work around this? Below is the code I used for the issue.
The code-behind of the wpf view - I used this to catch the event for WINDOWS CLOSE button:
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if (!closed)
{
e.Cancel = true;
FormFadeOut.Begin();
closed = true;
}
base.OnClosing(e);
}
This code is used to close the application when the fadeout ends:
private void FormFadeOutAnimation_Completed(object sender, EventArgs e)
{
this.Close();
}
In my xaml,I used this code in order to call the function to pop up the SAVE CHANGES message when it is closing:
cal:Message.Attach="[Event Closing] = [Action CloseApp2()]"
In my view model, the following function is called by the above xaml code:
public void CloseApp2()
{
// isClosing = true;
events.Publish(new IsClosingEvent());
// events.Publish(new ClearItemsEvent());
// events.Publish(new SwitchTimerOffEvent());
// Thread.Sleep(2000);
}
When the "IsClosingEvent" event is sent, the SAVE CHANGES message will appear if there are any changes made by the user.
Does anyone have any good idea of how to solve this issue?
Thanks for any helps in advance.
Charles
Use Window.Closing event instead of
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)

WinForms Dialog Form -- Close or Dispose?

I've inherited some code and wanted to run this modification by you all, my concern is memory management.
Let us say I have a "base" Form with a bunch of buttons that open "dialog" forms. What is the recommended pattern for opening the dialog forms? Currently we display the "dialog" form like so (in the "base" Form code, upon button click):
ChangePasswordForm frm = new ChangePasswordForm();
frm.ShowDialog();
Then close it like so (in the "dialog" form code):
private void bCancel_Click(object sender, EventArgs e)
{
this.Close();
//this.Dispose(); <-- this is what I am considering adding.
}
My rationale for adding Dispose is that I am worried if this form is displayed and closed many times that each time a new instance of the form is created and its resources are never really released -- is this correct? Also, if the form has the "close" X in the top right, should I put a Dispose() call in the FormClosed event as well?
Thanks in advance.
I would use a using statement:
using (var frm = new ChangePasswordForm()) {
frm.ShowDialog();
}
Combine this with a DialogResult:
private void bCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
Setting the DialogResult, will close the Dialog, and the caller/owner has some feedback.
And you don't have to worry about Close or Dispose.
According to MSDN you need to dispose under two conditions:
The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection.
MSDN Form.Close
Declaring the form in a using statement would be the appropriate way to handle this.
using (ChangePasswordForm frm = new ChangePasswordForm())
{
frm.ShowDialog();
}

Hotkeys in Silverlight?

Is there a way to create global keys in Silverlight? I added a KeyDown event handler to the topmost Page element. I can catch the key signal when elements like a Button, TextBox, Calendar, and RichTextBox have focus. But the DatePicker won't let me handle the key down event at the Page level. Any way to make a hotkey in non-OOB SL?
P.S. I am assuming that the DatePicker control behaves differently than others as it is still in the Silverlight Toolkit.
have you tried using the AddHandler method? With this method you can add a handler and define if you want to handle already handled events, too.
In my simple example I added it to the RootVisual in the app.xaml.cs.
private void Application_Startup(object sender, StartupEventArgs e)
{
this.RootVisual = new MainPage();
RootVisual.AddHandler(UIElement.KeyDownEvent, new KeyEventHandler(HandleKeyDown), true);
}
private void HandleKeyDown(object sender, KeyEventArgs e)
{
//Add your keyhandling code here
Debug.WriteLine(e.Key);
}
I tried it with a DatePicker and it works.
Hope this helps!
BR,
TJ
This may help you. The author provides two ways using HTML bridge (when your Silverlight does not have focus) and using the KeyUp event on Application.RootVisual.
I have not tried it myself so I wouldn't know if it's working.

WPF ComboBox DropDown part appears in the wrong place

I put several ComboBoxes on a XAML window. When I expand any of them, the DropDown part appears on the upper left corner of the screen.
I use Visual Studio 2008 C# Express. I don't remember this phenomenon when I used Visual Studio 2008 (Trial Version), though I use the same FrameWork (3.5).
It seems to be a bug.
Workaround:
Use Window.Show() instead with a custom logic to simulate the ShowDialog() behavior.
This appears to be a bug in WPF. In my case, I was trying to open a window in the Loaded event of another window. To get around this, I set a timer up to fire, then used a delegate to open the window (cannot open the window in a timer event because the calling thread that opens a window must be STA).
Edit - timer isn't necessary - didn't see the answer above just queue it on the dispatcher...
private delegate void DelegateOpenWindow();
private DelegateOpenWindow m_DelegateOpenWindow;
private Timer loginTimer = new Timer(200);
private void MainWindow1_Loaded(object sender, RoutedEventArgs e)
{
// create delegate used for asynchronous call
m_DelegateOpenWindow= new DelegateOpenWindow(this.OpenWindow);
// start a timer to fire off the open window.
loginTimer.Elapsed += loginTimer_Elapsed;
loginTimer.Enabled = true;
}
void loginTimer_Elapsed(object sender, ElapsedEventArgs e)
{
loginTimer.Enabled = false;
this.Dispatcher.BeginInvoke(m_DelegateOpenWindow);
}
void OpenWindow()
{
MyWindow w = new MyWindow();
w.Owner = this;
w.ShowDialog();
}
I started observing this (and other strange behavioral quirks) yesterday when I tried to "tweak" window sizes, shapes, colors, and invoke a log-on dialog from the Window.Loaded event handler. I had been doing this just fine in each of a dozen+ individual "MVVM" pattern apps. Yesterday, I decided to move this from each app's code behind into a consolidated code-behind base class, since the pre-processing had become common in all those apps. When I did, the drop-downs in two ComboBoxes in the log-in dialog suddenly appeared in the upper left corner of my screen. I seem to have "solved" it by using the following technique (your mileage may vary):
protected void WindowBaseLoadedHandler(object sender, RoutedEventArgs e)
{
...non-essential lines of code removed...
if (DataContext != null)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
/*----------------------------------------------------------------------
* Do we have a View Model? If so, perform standard VM Initialization...
*---------------------------------------------------------------------*/
this.IsEnabled = false;
LoginDlg loginDlg = new LoginDlg();
loginDlg.ShowDialog();
if (!loginDlg.Success)
{
/*-----------------------------------
* Log on failed -- terminate app...
*----------------------------------*/
...termination logic removed...
}
this.IsEnabled = true;
}));
}
WindowBaseLoadedHandler is the Loaded event handler. LoginDlg is a WPF app with a dialog containing two ComboBoxes.
Recap: After I consolidated the code into the Loaded event handler of the base class the ComboBox's drop down lists appeared in the upper left corner of my screen. Once I wrapped the logic into the Dispatcher.BeginInvoke call, the appropriate ComboBox behavior returned with lists below the current item.
I suspect WPF needs the application to return from the Loaded event to complete the layout system's initialization. That doesn't fully explain why it worked before, but I'll have to queue up my desire to hunt that "why" down for some rainy day in the future and celebrate overcoming the latest obstacle for today.
In any event, I hope someone finds this of use.
I'm using the latest .Net 4.5 and WPF framework and I still have this problem. One thing I noticed is that it only happen when there's an attached debugger. When the debugger is not attached, everything works fine.
I had the same problem on Visual Studio 2019.
Using window.Show() can help but it can ruin your design.
The solution is to open the window asynchronously.
var yourDialog= new YourDialog();
yourDialog.Owner = this;
TaskCompletionSource<bool?> completion = new TaskCompletionSource<bool?>();
this.Dispatcher.BeginInvoke(new Action(() =>
completion.SetResult(yourDialog.ShowDialog())));
bool? result = await completion.Task;
You can also create a more elegant solution by making the extension method:
public static class AsyncWindowExtension
{
public static Task<bool?> ShowDialogAsync(this Window self)
{
if (self == null) throw new ArgumentNullException("self");
TaskCompletionSource<bool?> completion = new TaskCompletionSource<bool?>();
self.Dispatcher.BeginInvoke(new Action(() => completion.SetResult(self.ShowDialog())));
return completion.Task;
}
}
And you can use it like this:
await dlgReview.ShowDialogAsync();
It’s a bug in WPF (not the only one, I'm afraid). It happened when I opened another window in the Loaded Event, something like:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Window selectionWindow = new SelectionWindow();
bool? result = selectionWindow.ShowDialog();
if (result == true)
RecordChanged();
}
I already found a workabout.

Resources