I´m a total C# noob, so please be indulgent with me ;)
I´m just working on an WPF Application and want to implement my program in the MVVM-pattern.
I want to write a simple HTML editor.
So at first my application consists of a menu, which owns the item "File". There you should be able to select between "New", "Open", "Save", "Save As" and "Close".
During my first steps with C# I wrote these functions in the CodeBehind-File of the MainWindow and it worked. But now I want to implement my program in a "cleaner" way by using the MVVM pattern. But I really have problems to understand this pattern and especially to implement the SaveDialog and the OpenDialog without CodeBehind.
private void Oeffnen_Click(object sender, RoutedEventArgs e)
{
//neuen OpenDialog anlegen
webBrowser2 = new WebBrowser();
DockPanel.SetDock(webBrowser2, Dock.Top);
this.DockPanel1.Children.Add(webBrowser2);
opendlg = new Microsoft.Win32.OpenFileDialog();
opendlg.Filter = "html files (*.html)|*.html|htm files (*.htm)|*.htm";
//opendlg.RestoreDirectory = true;
//öffne Opendialog
if (opendlg.ShowDialog() == true)
{
try
{
if (opendlg.OpenFile() != null)
{
filename = opendlg.FileName;
webBrowser2.Navigate("file:///" + filename); //Öffne html Datei
doc2 = webBrowser2.Document as IHTMLDocument2;
doc2.designMode = "On"; //Editierbarkeit aktivieren
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
So this is for example my CodeBehind for the FileOpen-function.
Can someone maybe explain me on the example of the Open or SaveDialog or anyway else, how to use the MVVM pattern with this kind of application?
Sorry if this question is too general. Please ask for details.
Thanks!
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have bound the openFileDialog control with button. On button event, I am calling the openFileDialog control.
Now, when I am running my application, the openFileDialog box gets open but does not select the file. The open button is not working.
Example code:
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk_1(object sender, CancelEventArgs e)
{
// logic written here
}
It was working fine earlier but now its not working.
You need to use the DialogResult to get the event of open confirmation by the user. Then you can use a stream to read the file. Here is some sample code (provided by MS in the MSDN - source:https://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog(v=vs.110).aspx):
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Some logic here
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Failed to open file. Original error: " + ex.Message);
}
}
}
Answer post edits
The included code shows the method openFileDialog1_FileOk_1 the "_1" at the end suggest to me that you had some issues binding the event. Perhaps there was at some point a method openFileDialog1_FileOk caused conflict.
You should check if the method is correctly bound to the event.
For that I will remit you to my answer to How to change the name of an existing event handler?
For abstract you want to see what method is bound to the event. You can do it from the properties panel, or by checking the form designer file (that is named something .Designer.cs for example: Form1.Designer.cs).
Addendum: Consider adding a break point in the event handler. It will allow you to debug step by step what is happening. Also, it will allow you notice if the event handlers is not being executed at all, which would suggest that the method is NOT correctly bound to the event.
Original Answer
OpenFileDialog Does not open files, it barely select thems and makes the selection available for your application to do whatever your applications is intended to do with those files.
The following is the usage pattern from the MSDN article linked above:
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show
(
"Error: Could not read file from disk. Original error: " + ex.Message
);
}
}
Now, observe that after cheking the result of ShowDialog - which returns once the dialogs is closed - the codes uses the method OpenFile to actually open the file. The result is a stream that you can process anyway you prefer.
Alternatively you can retrieve the selected files via the property FileNames, which returns an array of strings. If you have configured the dialog to only allow selecting asingle file you are ok to use FileName instead.
Addendum, if by "Open" you mean to invoke the default application associated with the selected file to open the file. You can accomplish that by passing the file path to System.Diagnostics.Process.Start.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string name = openFileDialog1.FileName;
object objOpt = Type.Missing;
var excelApp = new Excel.Application();
Excel.Workbook wbclass = excelApp.Workbooks.Open(name, objOpt,
true,
objOpt,
objOpt,
objOpt,
objOpt,
objOpt,
objOpt,
objOpt,
objOpt,
objOpt,
objOpt,
objOpt,
objOpt);
}
I created simple program for save/open practice. Made a setup and associated my program with my own datatype, called it .xxx (for practice).
I managed to Save and Open code and data from textbox but only from my program. Double click (or enter from windows-desktop) open up my WindowsForm as it is but there is an empty textbox. I want my saved file to be opened on double click in the same condition as when I open it from my program. How to set that up??
Here is the code of simple app (cant post images but it simple - got 1 label and 1 textbox with open and save buttons):
private void ButOpen_Click(object sender, EventArgs e)
{
textBox1.Text = "";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string data = Read(openFileDialog1.FileName);
textBox1.Text = data;
}
else
{//do nothing }
}
private string Read(string file)
{
StreamReader reader = new StreamReader(file);
string data = reader.ReadToEnd();
reader.Close();
return data;
}
private void ButSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Something|*.xxx";
DialogResult result = saveFileDialog1.ShowDialog();
string file = saveFileDialog1.FileName.ToString();
string data = textBox1.Text;
Save(file, data);
}
private void Save(string file, string data)
{
StreamWriter writer = new StreamWriter(file);
writer.Write(data);
writer.Close();
}
NOTE:
My similar question was marked as duplicate but it is not, and this question which was referenced as duplicate Opening a text file is passed as a command line parameter does not help me.It's not the same thing...
Just wanted to find out how to configure registry so windows understand and load data inside the file, or to file save data somehow so i can open it with double click.
So someone please help. If something is not clear I will give detailed information just ask on what point.
Thanks
MSDN has some information about this:
https://msdn.microsoft.com/en-us/library/bb166549.aspx
Basically you need to create an entry in the registry so that explorer.exe knows to launch your program when that file is activated (e.g. double-clicked).
Explorer will then pass the path to the file as an argument to your program.
I wanted to reference the Paint.NET assemblies directly and use a its functionality that way. i dont know how to use the .dll file PaintDotNet.Core.dll
and use it functionality in C# visual studio any helps. Please
want to reference to these assemblies: C:\Program Files\Paint.NET\PaintDotNet.*.dll Then poke around the classes in those namespaces.
Codes:-
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
string filename = "";
if (ofd.ShowDialog() == DialogResult.OK)
{
filename = System.IO.Path.GetFullPath(ofd.FileName);
}
// MessageBox.Show(filename, "file");
pictureBox1.ImageLocation = filename;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
DialogResult result = MessageBox.Show("Do you wish to continue?", "Save Changes", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
System.Diagnostics.Process.Start(#"C:\Program Files\Paint.NET\PaintDotNet.exe");
// here i need to perform the function like
//Open + O`
//ctrl + Shift + L)` then `
//(ctrl + Shift + G)`. then save
//`ctrl + Shift + S`
}
else
{
return;
}
}
Just follow the instruction to send the shortcut key to another application
Add this namespace to the class
using System.Runtime.InteropServices;
Then declare SetForegroundWindow function with DllImport statement. this will create object of that method which has been created in User32.dll
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
And add the following code to your button click or anywhere in your project. This code will navigate the OpenFileDialog to open the existing file in Paint.NET application.
private void button1_Click(object sender, EventArgs e)
{
Process p = Process.GetProcessesByName("PaintDotNet").FirstOrDefault();
if (p != null)
{
SetForegroundWindow(p.MainWindowHandle); //Set the Paint.NET application at front
SendKeys.SendWait("^(o)"); //^(o) will sends the Ctrl+O key to the application.
}
}
most of programmers made the mistake between Ctrl+O and Ctrl+o seems similar but, the ascii value of both key is different. So, make sure the key character is not in uppercase. You can also read the full information about SendKey method on msdn. You can make any key combination and send through the SendWait() method.
Just add one or some or all of the libraries to your project. as Measuring states then use the object explorer.
NOTE: never mind the .xaml stuff or the actual projects I am trying to render SharpDX D3D11 in a wpf app to make a map editor (and without the toolkit (don't ask me why. I am crazy)).
I swear I have the code last night are you trying to automate paint.net?
you will have to make a plug-in which would make the process way more streamlined than having to start a second app.
I would like to implement an open file dialog or file browser that additionally offers a "Preview" button to play the currently selected sound file (wave format in particular, other formats are not necessary for this application).
I could create my own form with various controls such as a treeview and listbox to show the folders and files, but I think I would be reinventing the wheel, or if nothing else going to a lot of work for something very simple. Do you recommend doing this?
Can I modify (inherit) the existing OpenFileDialog and add the sound-playing button to it somehow?
Is there some free library of custom file pickers that could be utilized? (Provided that the license allows inclusion in a commercial sense.)
Before you get carried away hacking the dialog, consider a simple solution first that leverages the FileOk event. Create a form named, say, frmPreview. Give it a constructor that takes a string. You'll need a Cancel and an OK button and code to play the file.
Display that form like this:
var dlg = new OpenFileDialog();
// Set other dlg properties...
dlg.FileOk += (s, cancel) => {
using (var prev = new frmPreview(dlg.FileName)) {
if (prev.ShowDialog() != DialogResult.OK) cancel.Cancel = true;
}
};
if (dlg.ShowDialog(this) == DialogResult.OK) {
// use the file
//...
}
Now, whenever the user clicks Open, your preview form shows up. The user can click Cancel and pick another file from the dialog.
Found this question whilst searching before asking my own. Possible slight simplification of Hans' answer is to use a standard Message Box rather than having to write your own form. Still a popup on a popup though.
private void btnSelect_Click(object sender, RoutedEventArgs e) {
var dlg = new Microsoft.Win32.OpenFileDialog {
DefaultExt = ".csv",
Filter = "Wav Files Only (*.wav)|*.wav",
InitialDirectory = "C:\\Windows\\Media\\",
CheckFileExists = true
};
dlg.FileName = "preselect the existing file if you wish";
dlg.FileOk += (s, cancel) => {
var player = new MediaPlayer();
player.Open(new Uri(dlg.FileName));
player.Play();
var msgres = MessageBox.Show(Path.GetFileName(dlg.FileName)+"\nUse this sound?", "Sound Playing", MessageBoxButton.YesNo);
if (msgres != MessageBoxResult.Yes) cancel.Cancel = true;
player.Stop(); //in case it is a long sound
};
var result = dlg.ShowDialog();
if (result != true) return;
//do whatever with dlg.FileName ...
}
Using a MessageBox provides a clean standard interface
Regarding point 2, I had thought the OpenFileDialog (or SaveFileDialog) weren't extendable in any way - they are provided by the OS.
But, it turns out they could be:
http://www.codeproject.com/KB/dialog/WPFCustomFileDialog.aspx
http://www.codeproject.com/KB/dialog/CustomizeFileDialog.aspx
The first one looks like what you're wanting to achieve.
Good luck.
can any expert help me out to solve a problem of burning a dvd using c#.net as a front end??
i need to select files from the listview in winform and then on button click i need to burn those multiple files in the dvd..
the concept is to select the multiple files from listview then on button click it should make a folder in some desired drive.. and then it should burn that complete folder in the dvd..this whole process should be performed during a single button click....
is there any way out??
the code should be compatible to use in .net2008 and windowsXP are the given codes compatible??
im using the componenet to get the dll/class lib. from (msdn.microsoft.com/en-au/vcsharp/aa336741.aspx) but its giving me error message "there are no components in d:\filepath\burncomponent.dll to be placed on the toolbox
private void button1_Click(object sender, EventArgs e)
{
XPBurnCD cd = new XPBurnCD();
cd.BurnComplete += new NotifyCompletionStatus(BurnComplete);
MessageBox.Show(cd.BurnerDrive);
DirectoryInfo dir = new DirectoryInfo(_burnFolder);
foreach (FileInfo file in dir.GetFiles())
{
cd.AddFile(file.FullName, file.Name);
}
cd.RecordDisc(false, false);
}
private void BurnComplete(uint status)
{
MessageBox.Show("Finished writing files to disc");
}
private void button2_Click_1(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowNewFolderButton = false;
fbd.Description = "Please select a folder";
fbd.RootFolder = System.Environment.SpecialFolder.DesktopDirectory;
if (fbd.ShowDialog() == DialogResult.OK)
{
_burnFolder = fbd.SelectedPath;
}
else
{
_burnFolder = string.Empty;
}
}
Check out http://msdn.microsoft.com/en-au/vcsharp/aa336741.aspx
One simple approach could be to use the command line tools dvdburn and cdburn, which are belonging to XP. For example take a look at this site.
Update
Yes, it is a console application, but you can start it within a .Net Application by using the Process class. And here you should especially take a deeper look into the StartInfo property and its members, cause here you can set the parameters or redirect the output into your program to get informations about what the program is doing.