WPF - How to close a file that was opened in RichTextBox - c#

On a click event of a button , I'm opening a file in RichTextBox of a WPF app as follows. I've another button for closing the file but need to figure out how to close that opened file after reading it but without exiting my entire WPF app.
Think of it as a scenario similar to what we have in Microsoft WORD application where you can open a WORD document by using File-->Open menu item, and then you can close it by using File-->Close menu item while keeping the WORD application still open with top Ribbon. In my case, I've a toolbar on top with open and close button that I need to perform similar Open/Close file operations on:
private void BtnOpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Rich Text Format (*.rtf)|*.rtf|All files (*.*)|*.*";
if (dlg.ShowDialog() == true)
{
FileStream fileStream = new FileStream(dlg.FileName, FileMode.Open);
TextRange range = new TextRange(mainRTB.Document.ContentStart, mainRTB.Document.ContentEnd);
range.Load(fileStream, DataFormats.Rtf);
}
}

If you want to "close" the file whose content is shown in a RichTextBox, I think it'd be enough to clear the RichTextBox and to dispose your resources.
By "disposing your resources", I mean closing your FileStream or wrap it in a using, for example.

Related

How to simulate pressing save/enter in SaveFileDialog

I'm creating an application to automate some processes. One of them is creating docx file from the dotx template.
Steps are quite easy: app opens MS Word with test.dotx file and SaveAs it to c:\temp as a test.docx. It should be as close to user's actions as possible. When the file is opened (from dotx so it is docx already) all I need is to open SaveAs dialog and push "save" (or just "enter", because focus is set on "save" button).
The problem is how to "hit" the save/enter. I tried SendKeys but I am in ShowDialog() which is waiting for the result and cannot perform SendKeys at the moment. Of course if I press enter from keyboard or cklick on "Save" all works perfectly, but this one "press" I'd like to do from the code. Could you please point me how to solve this (if it is possible at all)? Thank you.
Here is the part of the code I'm strugglig with:
SaveFileDialog saveFileDialog1 = new SaveFileDialog
{
InitialDirectory = #"C:\Temp\",
DefaultExt = "docx",
FileName = "test"
};
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
object FileName = saveFileDialog1.FileName;
doc.SaveAs(ref FileName);
}
If hit the save/enter is your requirement, the recommendation is use Spy++ (this Tool can be installed by Visual Studio Installer) to capture both: "the dialog with save button" and "save button" alias/class; then, programming with C# PInvoke (for example, using FindWindow and FindWindowEx) to send/post message to simulate this "save" button.

Select File and Continue Program In WPF

I've been trying to follow tutorials and various Stack Overflow posts, etc. to implement an OpenFileDialog to select a file. The problem is, it seems I can't get my program to continue with the rest of the logic. Not entirely sure if it has something to do with the fact I'm trying to open the file dialog inside my main window or what. Consider the following snippet:
public MainWindow()
{
InitializeComponent();
string file = "";
// Displays an OpenFileDialog so the user can select a file.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Files|*.txt;*.out";
openFileDialog1.Title = "Select a File";
openFileDialog1.ShowHelp = true;
// Show the Dialog.
// If the user clicked OK in the dialog and
// a file was selected, open it.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//file = openFileDialog1.FileName;
//file = openFileDialog1.OpenFile().ToString();
//openFileDialog1.Dispose();
}
openFileDialog1 = null;
Console.WriteLine("File path is: " + file);
As you can see, I've even tried setting the "Help" value to true before the dialog finishes. I've tried to select both the file name for the file string, etc. but to no avail - the program seems to simply wait after the file is selected from the dialog. Would anyone here have a suggestion for a solution?
Previously I had the same problem with WPF. When you are working with WPF, System.Windows.Form Namespace is not included to your Project references;
and in the other hand actually, there are two OpenFileDialog, the first is System.Windows.Forms.OpenFileDialog (this is what you have) and the second is Microsoft.Win32.OpenFileDialog. if you want to get your code to work you must add System.Windows.Forms into your references:
Solution Explorer -> YourProject -> References (Right Click and Add Reference...) -> Assembly -> Framework -> Find And Select System.Windows.Forms -> OK
and the Next Solution is to use Microsoft.Win32, it's pretty easy. just add this Namespace into your code file and Change your code like this:
string file = "";
// Displays an OpenFileDialog so the user can select a file.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Files|*.txt;*.out";
openFileDialog1.Title = "Select a File";
// Show the Dialog.
// If the user clicked OK in the dialog and
// a file was selected, open it.
if (openFileDialog1.ShowDialog() == true)
{
file = openFileDialog1.FileName;
//file = openFileDialog1.OpenFile().ToString();
//openFileDialog1.Dispose();
}
openFileDialog1 = null;
Console.WriteLine("File path is: " + file);
OpenFileDialog.ShowDialog() is a modal method:
FileDialog is a modal dialog box; therefore, when shown, it blocks the
rest of the application until the user has chosen a file. When a
dialog box is displayed modally, no input (keyboard or mouse click)
can occur except to objects on the dialog box. The program must hide
or close the dialog box (usually in response to some user action)
before input to the calling program can occur.
This means that invoking this method will block your main thread until the dialog box is closed. A few of the options you have are:
Invoke the FileDialog after the main window is initialized.
Invoke the FileDialog from a thread. In this case, be careful to synchronize.

how to change the background image of a form using open file dialog on another form

I have a query that. I have a splash form that is my first form of the project and I want to change the background image of that form after that is closed. For example my software starts and after splash form and in setting I have a function to change the background image of the splash form. Can I change the background image when the form is closed? (as my splash form is closed when user enters the setting form).
I have written this code form changing the background image but I don't know how to change the form image when the splash form opens it should open changing the image from the open file dialog.
My code is:
var FD = new System.Windows.Forms.OpenFileDialog();
FD.Filter = "jpeg files|*.jpg";
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
BackgroundImage = Image.FromFile(FD.FileName);
}
Ok try the below
you already set a background image for your splash screen
eg : it location was c:\sam.jpeg
Now try the below code on form close event
System.IO.File.Delete(#"C:\Sam.jpeg");
Image.FromFile(FD.FileName).Save(#"C:\Sam.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
now it delete the old file and set the new image on old name...
at the time of reload it shows the new background image...
You load the splash image from somewhere, so then just replace that image with the one selected by the user with the OpenFileDialog and then the new image will be loaded the next time the splash is shown.
EDIT: Further explanation
An example of a solution. Store the image in the same folder as the application (for example: "splash.png") and then you can load that on the Splash Form Load event for example. Now, when the user wants to replace the image from settings with the open file dialog, you simply have to copy the file selected to the application's folder (Application.StartupPath should get you the path to the app folder) and overwrite the old splash.png (maybe you can rename the old one before overwriting or something) and then the next time the application will load, that's the image the Splash form will load.
This is a simple solution that can be improved upon, but as a first attempt it should produce the result you want.

File Upload in C# windows Application

In my C# Windows application I want to upload a pdf file but in my toolbox I cannot find a FileUpload control.
How can I go about and uploading a pdf file in a C# windows application.?
regards
After you put a OpenFileDialog control on your form, let's say that you click a button and:
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
//Do whatever you want
//openFileDialog1.FileName .....
}
}
it goes something like this :-)
You can use OpenFileDialog to get the filename of the file you need and then .NET File object to read data from the file. You might need a control being able to display a PDF file. Please read the following:
Viewing PDF in Windows forms using C#

How to make a .txt appear after clicking a button

I asked this question a minute ago and was not specific enough so let me try again.
I am trying to generate a report of inventory information that is already made and have it update from the user input into text boxes on the form and then have a button to make the .txt file of the report show to the screen and have the updated information on it.
I have the GUI created and have the button created and the .txt file is created. I just need to know how to make it where I can click the button and have the .txt file appear to the screen.
Using System.Diagnostics;
...
String filename = "C:\\....\data.txt"; \\ File Created With Information
Process.Start(filename); \\ Will open file with default program
The above code can be used to open an external program to display your text file.
As usual I recommend using try/catch since you are dealing with external I/O (files).
You can just start the notepad process with your *.txt file as the argument and start the process can't you?
Found this link that might help you: http://www.csharp-station.com/HowTo/ProcessStart.aspx
Assign a click event to your button (in your class constructor for instance):
button.Click += new EventHandler(button_Click);
In the event, start notepad.exe in a new process:
void button_Click(Object sender, EventArgs e) {
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "notepad.exe";
startInfo.Arguments = "C:\Path\To\My\file.txt";
Process.Start(startInfo);
}

Categories