Opening media file with button press - wpf

I have one button on my wpf called 'Open Media' with click event and a MediaElement to play media.
I want to open a media file by pressing that button.
It's giving me run time exception 'System.NotSupportedException' on line 'mePlayer.Play()'. How to achieve this using following code:
private void OpenMediaButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openMedia = new OpenFileDialog();
openMedia.Title = "Open Media";
openMedia.Filter = "mp4 files(*.mp4)|*.mp4";
openMedia.InitialDirectory = #"C:\";
openMedia.RestoreDirectory = true;
if (openMedia.ShowDialog() == true)
{
mePlayer.Source = new Uri(openMedia.FileName);
mePlayer.Position = TimeSpan.FromSeconds(1);
mePlayer.Play();
}
}

Related

How to hide the Download dialog in WebView2 while downloading page content or printing with "Save as PDF" option?

I know how to subscribe to the CoreWebview2.DownloadStarting event and use handled = true to stop the Download dialog from showing while a download (i.e. an image) is being made, but the problem is the DownloadStarting event never fires if you right click on a web page and choose "Save as" or "Print > Save as PDF", even though the Download dialog will appear as if a regular download was being made. Does anyone know any workaround for this?
My code:
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
if (webView != null)
webView.Dispose();
webView = new WebView2();
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting;
panel1.Controls.Add(webView);
webView.Dock = DockStyle.Fill;
webView.Source = new Uri("https://www.microsoft.com");
}
private void CoreWebView2_DownloadStarting(object sender, CoreWebView2DownloadStartingEventArgs e)
{
e.Handled = true;
}
I just found a solution:
subscribe to CoreWebView2.IsDefaultDownloadDialogOpenChanged event:
webView.CoreWebView2.IsDefaultDownloadDialogOpenChanged += webView_CoreWebView2_IsDefaultDownloadDialogOpenChanged;
Close the Download dialog if it's open:
private void webView_CoreWebView2_IsDefaultDownloadDialogOpenChanged(object sender, object e)
{
if (webView.CoreWebView2.IsDefaultDownloadDialogOpen) webView.CoreWebView2.CloseDefaultDownloadDialog();
}

How do I code a Save button in WPF to save CSV Files after importing them in my application and editing it?

Im using this Import Methode, and after editing the File in my application I want to have a button to save the File as a "new File" so the source doesnt get changed only a edited duplication is created.
//import button
private void btn_Import_Click(object sender, RoutedEventArgs e)
{
//delete the filename from the textbox so they dont overlap
tbx_FileName.Clear();
//openFileDialog for file Import
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.InitialDirectory = #"C:\";
var result = dlg.ShowDialog();
tbx_FileName.Text = dlg.FileName;
DataContext = CSVTable.ReadFile(dlg.FileName);
}
//save button
private void btn_Save_Click(object sender, RoutedEventArgs e)
{
//saveFileDialog for file Save
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.InitialDirectory = #"C:\";
dlg.Filter = "CSV file (*.csv)|*.csv|All Files (*.*)|*.*";
var result = dlg.ShowDialog();
if (result.HasValue && result.Value)
{
//Save the file, assuming the DataContext is plain text (i.e. string)
File.WriteAllText(dlg.FileName, DataContext);
}
}

Using OpenFileDialog with windows form not opening

I am making a GUI with a windows form and OpenFileDialog is not opening on button click.
I am using the following code and nothing happens when I click on my button designated as button1.
System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
Stream^ myStream;
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
openFileDialog1->InitialDirectory = "c:\\";
openFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1->FilterIndex = 1;
openFileDialog1->RestoreDirectory = true;
if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
if ((myStream = openFileDialog1->OpenFile()) != nullptr)
{
String^ strfilename = openFileDialog1->FileName;
String^ Readfile = File::ReadAllText(strfilename);
MessageBox::Show(Readfile); // This is a test line
//myStream->Close();
}
}
}

How to stop a new window to be opened every time?

I have a WPF application in which on a click of a menu item a window is opened. If the same menu item is clicked again when the window is already open, it is opening a new window but I don't want a new window to be opened every time.
What I need is, if the window is already open, the same window should be focused not a new window.
//First we must create a object of type the new window we want the open.
NewWindowClass newWindow;
private void OpenNewWindow() {
//Check if the window wasn't created yet
if (newWindow == null)
{
//Instantiate the object and call the Open() method
newWindow= new NewWindowClass();
newWindow.Show();
//Add a event handler to set null our window object when it will be closed
newWindow.Closed += new EventHandler(newWindow_Closed);
}
//If the window was created and your window isn't active
//we call the method Activate to call the specific window to front
else if (newWindow != null && !newWindow.IsActive)
{
newWindow.Activate();
}
}
void newWindow_Closed(object sender, EventArgs e)
{
newWindow = null;
}
I think this solve your problem.
Att,
If your opened windows is used as simple dialog box you can use following code
window.ShowDialog();
when the dialog will show you cannot press any menu items unit you close this window
A rather brute force approach like this also works:
bool winTest = false;
foreach (Window w in Application.Current.Windows)
{
if (w is testWindow)
{
winTest = true;
w.Activate();
}
}
if (!winTest)
{
testWindow tw = new testWindow();
tw.Show();
}
You can create a field and check if it's set:
private Window _dialogue = null;
private void MaekWindowButton_Click(object sender, RoutedEventArgs e)
{
if (_dialogue == null)
{
Dialogue diag = new Dialogue();
_dialogue = diag;
diag.Closed += (s,_) => _dialogue = null; //Resets the field on close.
diag.Show();
}
else
{
_dialogue.Activate(); //Focuses window if it exists.
}
}

wpf- Application_Startup - load dialog window THEN mainwindow

I have a wpf application and I created a logon window which is used to build the application's connection string. I am having issues closing the first dialog and spinning open the MainWindow behind it. I think a close event is bubbling out of the logon dialog and getting stuck in the MainWindow because as soon as I create the MainWindow object in the codebehind and call Show() it just moves right past my Startup event handler and into my constructor then the onClosing handlers of the MainWindow without ever showing the window itself. The app.xaml has the ShutdownMode="OnMainWindowClose" specified.
private void Application_Startup(object sender, StartupEventArgs e)
{
try
{
Chooser thechooser = new Chooser();
thechooser.ShowDialog();
}
catch (Exception ex)
{
}
//initialize datalayer
dataLayer = new Mxxx41.DAL(this.CurrentConnectionString);
MainWindow appmainwindow = new MainWindow();
Application.Current.MainWindow = appmainwindow;
appmainwindow.Activate();
appmainwindow.Show();
}
private void LogInButton_Click(object sender, RoutedEventArgs e)
{
//get ip from listbox selection
XmlElement currentelement = (XmlElement)Listbox.SelectedItem;
string ip = ((string)currentelement.Attributes["IP"].Value);
string instancename = string.Empty;
if (!((string)currentelement.Attributes["InstanceName"].Value == string.Empty))
{
instancename = ((string)currentelement.Attributes["InstanceName"].Value);
}
//ping that IP
Boolean pingresult = ping.PingHost(ip);
Boolean sqlresult = false;
if (pingresult)
{
if (!(String.IsNullOrEmpty("instancename")))
{
ip = string.Format("{0}\\{1}", ip, instancename);
}
//build connection string with that IP
string connstr = BuildConnStr(ip);
//create datalayer
Mxxx41.DAL datalayer = new Mxxx41.DAL(connstr);
//validate credentials
DataSet data = datalayer.getDataSet("login_checkcredentials", CommandType.StoredProcedure, datalayer.CreateParameter("#username", SqlDbType.VarChar, this.UsernameTextbox.Text), datalayer.CreateParameter("#password", SqlDbType.VarChar, this.PasswordTextbox.Text));
if (data.Tables[0].Rows.Count > 0)
{
sqlresult = true;
//log in user
//build new user code omitted for brevity
App myAppReference = ((App)Application.Current);
myAppReference.CurrentUser = thisuser;
myAppReference.CurrentConnectionString = connstr;
//close window
this.Close(); //this is the close event I think is causing issues.
}
}
else
{
ErrorLabel.Content = string.Format("{0}{1}", "could not ping selected Host :", ip);
}
//return true
}
public MainWindow(){
this.InitializeComponent();
this.SideBarExpander.IsExpanded = true;
this.Loaded += onLoaded;
this.Closed += onClosed;
this.Closing += onClosing;
try
{
//this.DataLayer = ((Mxxx41.DAL)MyDemoApp.App.Current.Properties["DataLayer"]);
App myAppReference = ((App)Application.Current);
this.DataLayer = myAppReference.GetDataLayer();
}
catch //catch everything for the moment
{
this.DataBaseConnectionError = true;
}
ExceptionList = new List<Error>();
}
Can someone help me out with this behavior?
The problem is probably with ShutdownMode="OnMainWindowClose". Wpf considers the first window opened to be the "main window". In your case, wpf sees your logon window as the main window and exits your application when it closes.
Try changing the shutdown mode to OnLastWindowClose or OnExplicitShutdown.
From MSDN:
OnMainWindowClose: An application shuts down when either the main window closes, or Shutdown is called.
OnExplicitShutdown: An application shuts down only when Shutdown is called.

Resources