Closing all Windows in a C# WPF application - c#

I'm creating a little WPF app in VS2013Express and I've come across a little problem.
You see, there are three windows, MainWindow, LatAndLongDialog, TimeCitiesDialog.
`LatAndLongDialog` and `TimeCitiesDialog` are opened from MainWindow (with the click of a button).
I want all the other windows to close when the `Closed()` event is called on `MainWindow`.
The code on MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace GlobalTime_ELITE_for_WPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
UserDescText.Content =
"Select a TimeCity or enter the latitude and longitude in \n" +
"to view the World Time there. Or, select another one of the\n" +
"options below to do that. Go to Help by clicking on the link\n" +
"on the upper-right corner of the window to view everything you\n" +
"can do.";
this.Closed += CloseOff;
}
private void OpenTimeCitiesDialog(Object Sender, EventArgs E)
{
TimeCitiesDialog ObjectReference = new TimeCitiesDialog();
ObjectReference.Show();
}
private void OpenLatAndLongDialog(Object Sender, EventArgs E)
{
LatAndLongDialog ObjectReference = new LatAndLongDialog();
ObjectReference.Show();
}
private void CloseOff(Object Sender, EventArgs E)
{
this.Close();
TimeCitiesDialog tcdor = new TimeCitiesDialog();
LatAndLongDialog laldor = new LatAndLongDialog();
}
}
}
How can I close them all? Please help!

The proper way to shutdown a WPF app is to use Application.Current.Shutdown() . This will close all open Windows, raise some events so that cleanup code can be run, and it can't be canceled.
Environment.Exit() terminates the application immediately even if other threads are executing.
You should also consider setting the Owner on non-main Windows. The behavior will likely be more like what you would expect in regards to Z-order, minimizing, and maximizing. As an added bonus, the owned windows will automatically close when the owner Window closes.

private void CloseAllWindows()
{
for (int intCounter = App.Current.Windows.Count - 1; intCounter >= 0; intCounter--)
{
App.Current.Windows[intCounter].Close();
}
}
Close all opened current windows.

Use this instead this.Close()
Environment.Exit(0);
this will force everything to close

If you keep track of the Dialogs outside of the scope of the methods you use to open them, you can call which ever methods on those Dialogs you wish from anywhere within the Class. Here I have them as Class variables and they are instantiated there but not shown until you press the buttons. You can also create "Close" buttons for those specific windows and call their .Close() methods when ever you wish. That will allow you to open and close them at will. You can also call their .Close() methods when the main form closes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace GlobalTime_ELITE_for_WPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
TimeCitiesDialog tcDialog = new TimeCitiesDialog();
LatAndLongDialog lalDialog = new LatAndLongDialog();
public MainWindow()
{
InitializeComponent();
UserDescText.Content = "Select a TimeCity or enter the latitude and longitude in \n" +
"to view the World Time there. Or, select another one of the\n" +
"options below to do that. Go to Help by clicking on the link\n" +
"on the upper-right corner of the window to view everything you\n" +
"can do.";
this.Closed += CloseOff;
}
private void OpenTimeCitiesDialog(Object Sender, EventArgs E)
{
tcDialog.Show();
}
private void OpenLatAndLongDialog(Object Sender, EventArgs E)
{
lalDialog.Show();
}
private void CloseOff(Object Sender, EventArgs E)
{
// Close the dialogs first, then allow this method
// to end which will finish the this.Close() process.
tcDialog.Close();
lalDialog.Close();
}
}
}

Related

When opening one dynamic created button all buttons are opening

I am testing a small app where main window has a text box for entry, user clicks add (List Add in code) and it updates a simple list. In addition to the list update a dynamic button will be created in a wrap panel. The idea is the user then can click what ever entry they need to update and it load the second window with that entry correlated to an index in the list.
I have code that works for the most part but am blanking on what I believe is something trivial. If there is 3 buttons created and I go to click button 3 it will pop up all entries. So three windows with their assigned index. I just need the one window to show for the button that was clicked. I have played around and this particular issue is escaping me.
I have searched for a similar answer but came up short over the past few days.
MainWindow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
List<string> listA = new List<string>();
private int x = 1;
private int t = 1;
private void addBtn_Click(object sender, RoutedEventArgs e)
{
listA.Add(listBx.Text);
Button btns = new Button();
btns.Width = 70;
btns.Height = 30;
btns.Content = "Button " + x;
btns.Name = "Btn" + t;
btns.Click += (s, t) =>
{
for (int index = 0; index < listA.Count; index++)
{
EditWindow win = new EditWindow();
win.updateBx.Text = listA[index];
win.Show();
}
};
btnPanel.Children.Add(btns);
x++;
t++;
}
}
}
Second window (no code here yet, update btn will rewrite list index it correlates with:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace TestApp
{
/// <summary>
/// Interaction logic for EditWindow.xaml
/// </summary>
public partial class EditWindow : Window
{
public EditWindow()
{
InitializeComponent();
}
private void updateBtn_Click(object sender, RoutedEventArgs e)
{
}
}
}
I am not familiar with c# but the reason is i guess the loop in the click function. It does what you said. Instead of loop you should only use the current listA element.
In your button event handler, you are using a for loop to open an EditWindow for every entry in the list. Instead, only open one EditWindow and populate it with the specified entry.

Why do I have a compiler error (CS1503) in this Ozeki file?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Ozeki.Camera;
using Ozeki.Media;
using Ozeki;
using System.Windows.Media;
namespace BasicCameraViewer
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private VideoViewerWPF _videoViewerWPF;
private BitmapSourceProvider _provider;
private IIPCamera _ipCamera;
private WebCamera _webCamera;
private MediaConnector _connector;
public MainWindow()
{
InitializeComponent();
_connector = new MediaConnector();
_provider = new BitmapSourceProvider();
SetVideoViewer();
}
private void SetVideoViewer()
{
_videoViewerWPF = new VideoViewerWPF
{
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch,
Background= Brushes.Black
};
CameraBox.Children.Add(_videoViewerWPF);
_videoViewerWPF.SetImageProvider(_provider);
}
#region IP Camera Connect/Disconnect
private void ConnectIPCamera_Click(object sender, RoutedEventArgs e)
{
var host = HostTextBox.Text;
var user = userTextBox.Text;
var pass = Password.Password;
_ipCamera = IPCameraFactory.GetCamera(host, user, pass);
if (_ipCamera == null) return;
_connector.Connect(_ipCamera.VideoChannel, _provider);
_ipCamera.Start();
_videoViewerWPF.Start();
}
private void DiconnectIPCamera_Click(object sender, RoutedEventArgs e)
{
_videoViewerWPF.Stop();
_ipCamera.Disconnect();
_ipCamera.Dispose();
_connector.Disconnect(_ipCamera.VideoChannel, _provider);
}
#endregion
}
}
Can somebody tell me what I could do? It tells me that i can not convert the _videoViewerWPF.SetImageProvider(_provider) line from Ozeki.Media.BitmapSourceProvider to Ozeki.Media.IImageProvider and i have absolutely no idea what to do that it could work.
I tried several times to do something, but I dont even know what I´m doing.
I would be thankfull if somebody could help me so I can finish this.
I came across the same issue after following the Ozeki video C# camera tutorial #3 - Camera viewer on YouTube.
It may be that the API has moved on since that video because sample code on the Ozeki Website (How to connect to an RTSP camera and display the picture in C#) uses a DrawingImageProvider instead of a BitmapSourceProvider:
...
private DrawingImageProvider _provider = new DrawingImageProvider();
...
...and then (for a WPF app):
_videoViewerWpf.SetImageProvider(_provider);
In my case, this fixed the compiler error and I can now display RTSP video in a WPF app.

ProgressBar not starting, not going in foreach loop until window not closed

I work on an export plugin to export revit models to database.
To do this, my main window is calling ExportEngine which is a Window:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using UserConnect;
using System.Collections.ObjectModel;
using System.IO;
namespace UserConnect
{
public partial class ExportEngine : Window
{
private List<Component> components = new List<Component>();
private static String zoneName = "REVIT";
private User user;
private Server neo4j = new Server("172.16.1.104", 8000);
public ExportEngine(User userp)
{
user = userp;
InitializeComponent();
}
public void addComponent(Component c)
{
components.Add(c);
}
public bool save()
{
this.ShowDialog();
float progress = components.Count / 100;
foreach (Component c in components)
{
//Here is my export request, working good
pbStatus.Value+=progress;
}
this.Close();
return result;
}
}
}
I call this in Main :
db = new ExportEngine(user);
foreach(String name in mats)
{
Component c = new Component(name, "m2",1);
db.addComponent(c);
}
db.save();
I don't understand why my save() starts only after I close the progressbar Window, and this progressbar doesn't move at all (no progress).
save doesnt run until windows is closed
ShowDialog does not return until the window you are showing is closed. That explains why it does not run until the windows closes.
Progress bar doesn't update
Try this.
pbStatus.MaxValue = components.Count; //make sure you set the max value
foreach (Component c in components)
{
pbStatus.Value+= 1; //increment by one item as you have processed on item.
}

Trying to make a very simple speech recognition windows form project

I followed a very basic tutorial (forgot the link) and it all seems straightforward, but I don't seem to be getting the output I want. Here is my main form class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Speech.Recognition;
namespace OralNotes.Alpha
{
public partial class MainForm : Form
{
private SpeechRecognitionEngine recognitionEngine;
public MainForm()
{
InitializeComponent();
recognitionEngine = new SpeechRecognitionEngine();
recognitionEngine.SetInputToDefaultAudioDevice();
recognitionEngine.SpeechRecognized += (s, args) =>
{
foreach (RecognizedWordUnit word in args.Result.Words)
{
if (word.Confidence > 0.8f)
txtNotes.Text += word.Text + " ";
}
txtNotes.Text += Environment.NewLine;
};
recognitionEngine.LoadGrammar(new DictationGrammar());
}
private void btnStart_Click(object sender, EventArgs e)
{
recognitionEngine.RecognizeAsync();
}
private void btnStop_Click(object sender, EventArgs e)
{
recognitionEngine.RecognizeAsyncStop();
}
}
}
And you probably don't need this, but here it is anyway:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace OralNotes.Alpha
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
I click start and talk, and nothing happens.
UPDATE*
ok so this is working, if I adjust this line
if (word.Confidence > 0.8f)
to a lower number I get a word or two in. Not transcribing sentences or anything, is there a way to make this have better recognition?
It seems that the engine that you are using returns a confidence value on every word it hears.
I suspect that the confidence values range from 0-1. Which means that if you lower the value from 0.8 you are making the engine more tolerant to words. Maybe it is the quality of your mic?

Cannot download a subsite with a video

I've made a simple program (closely resting on this example) that visualises my problem. It only downloads a file from specified URL, nothing more; everything was OK until I tried with such data:
http://www.youtube.com/watch?v=pqaARDsiJv4
Surprisingly, nothing happens. Why it doesn't download neither the related video nor the HTML source code?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.IO;
using System.ComponentModel;
namespace downloader
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void DownloadButton_Click(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
string fileName;
try
{
fileName = System.IO.Path.GetFileName(URLBox.Text);
Uri currentURL = new Uri(URLBox.Text);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
client.DownloadFileAsync(currentURL, fileName);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
progressBar.Value = 0;
}
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download Completed!");
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
}
}
For such an URL this line...
fileName = System.IO.Path.GetFileName(URLBox.Text);
...sets fileName to "watch?v=pqaARDsiJv4", which is not a legal file name.
I don't think that you can download a video from Youtube like that. I will refer you to a Stack Exchange question from last year regarding downloading content from Youtube; there are many links and even a method for doing it. But all of these solutions are 3 years old, they may no longer work now; that's part of the problem with what you want to do; Google is constantly making changes, which will most likely break any current solutions.
You can see if any of the solutions provided here still work: https://stackoverflow.com/questions/1852029/how-can-i-download-youtube-videos-using-net-code
Or use the information provided to create your own.

Categories

Resources