Question: Is there any way to detect the occurrence of a file load in a RichTextBox (RTB) of a WPF app? I haven't find such an event in this list of events; or maybe there is some event in that list that can be used for a work around to achieve the following:
Background I'm allowing user to load a file in the RTB and close it after making changes (if needed). But before the user closes the file my app checks if the changes were made by placing bTextChanged flag in the TextChanged event. But I noticed that the TextChanged event is triggered even when a file is loaded. And even worst, the event is triggered for every character of the newly loaded file - that eventually can degrade the performance of the app if the loaded file is too long. so maybe there is a work around to make the TextChanged event triggered only when a text in the file is changed after the file was loaded.
public partial class MainWindow : Window
{
string sgFileName = "";
bool bTextChanged = false;
....
....
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)
{
sgFileName = dlg.FileName;
FileStream fileStream = new FileStream(sgFileName, FileMode.Open);
TextRange range = new TextRange(mainRTB.Document.ContentStart, mainRTB.Document.ContentEnd);
range.Load(fileStream, DataFormats.Rtf);
}
}
private void MainRTB_TextChanged(object sender, TextChangedEventArgs e)
{
bTextChanged = true;
}
private void BtnCloseDocument_Click(object sender, RoutedEventArgs e)
{
if (bTextChanged)
{
MessageBoxResult result = MessageBox.Show("Content has changed, do you want to save the changes?", "Content has Changed!", MessageBoxButton.YesNoCancel);
switch (result)
{
....
}
}
}
....
....
}
Related
I'm working with window forms on c# I'm trying to open a file using openfile dialog when I browse to my file and open it the open file dialog keeps on showing many times .
That's my code for opening a file :
private void OpenBtn_Click(object sender, EventArgs e)
{
// Create OpenFileDialog
OpenFileDialog dlg = new OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".xml";
dlg.Filter = "XML Files (*.xml)|*.xml";
// Display OpenFileDialog by calling ShowDialog method
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK)
{
pathtext.Text = dlg.FileName;
sourceName = dlg.FileName;
}
// destFile = resultFile.Name;
if (pathtext.Text != null)
{
createBtn.Enabled = true;
}
}
and this event handler of the method in the form load
OpenBtn.Click += new EventHandler(this.OpenBtn_Click);
I can't see where did I miss the thing.
The only way I can reproduce your bug is when I double click the button in the designer so that it creates an automatic event handler which you can see in the event properties:
If I then in addition to that add inside the code a manual registration of the event Click for example in the Load event:
private void Form1_Load(object sender, EventArgs e)
{
button2.Click += new EventHandler(this.OpenBtn_Click);
}
Then I will get the behaviour that the dialog pops up twice. If I do it one more time:
private void Form1_Load(object sender, EventArgs e)
{
button2.Click += new EventHandler(this.OpenBtn_Click);
button2.Click += new EventHandler(this.OpenBtn_Click);
}
It will pop up 3 times! It is very likely that you register this event in a loop. So when the first one is executed all others just follow up. Remove the manual registering line and put the event handler name simply into the event properties.
EDIT: The main problem is the operator += it adds the delegates to an internal list as described in this answer.
I've a datagridview for display data from Text file. Then, i've a button that have function to delete content on Text file (return it to 0 bytes).
But why event execute (by clicking button), the datagrid doesn't refresh even using .refresh() function. Here's my code on button that deleting content of file text.
private void button1_Click(object sender, EventArgs e)
{
File.WriteAllText("Transaction.txt", String.Empty);
dataGridView1.Refresh();
}
PS : The datagridview would change (empty of course) only after re-launch Windows Form.
You will need BindingList class to bind data to your datagridview:
var _bindingList = new BindingList<string>();
And in your form constructor:
public MyForm
{
InitializeComponent();
myDataGridView.BindingSource = _bindingList;
}
Create a timer to monitor the change of file:
DateTime lastWriteTime = DateTime.Now
private void timer_tick(object sender, EventArgs e)
{
FileInfo f = new FileInfo("C:\\myFile.txt");
if ( lastWriteTime == f.LastWriteTime) return;
lastWriteTime = f.LastWriteTime;
UpdateBindingList();
}
private void UpdateBindingList()
{
_bindingList.Clear();
//then read the file and add items to _bindingList.
}
To start, I'm a newbie with C# Programming and I've tried googling for solutions about my problem but it seems that i cannot find one, or simply too unlucky or too blind to spot one. I'm using Microsoft Visual Studio 2005.
Anyways. I was assigned to modify/create an automated test environment input application. The said application already has a function to run/start a CANoe program with a pre-defined file or if it's already running, stop the program.
private void button1_Click(object sender, EventArgs e)
{
// Execute CANoe(Obtain CANoe application objectg)
mApp = new CANoe.Application();
mMsr = (CANoe.Measurement)mApp.Measurement;
try
{
mApp.Open("C:\\Users\\uidr3024\\Downloads\\SRLCam4T0_Validation_ControlTool\\cfg\\SVT_SRLCam4T0_025B.cfg", true, true);
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
// Finish CANoe
if (mApp != null) {
mApp.Quit();
}
// Release the object
fnReleaseComObject(mMsr);
fnReleaseComObject(mApp);
}
What I wanted to do now is to have an OpenFileDialog box that will show a selection of files and user will be able to browse and select any file to start the CANoe program with the selected file and not just the file path that's been input in the code along the "mApp.Open()" syntax. I've tried this:
private void button5_Click_1(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\Users\uidr3024\Downloads\SRLCam4T0_Validation_ControlTool\cfg";
openFileDialog1.Title = "Browse Configuration Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.Filter = "CANalyzer/CANoe Configuration (*.cfg)|*.cfg |All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
}
I've tried this code that I often see in the Web and in the Tutorials but I don't know how to incorporate it with the button for running the CANoe program so that when user clicks the Open button from the Dialog Box, the file path would be shown in the textbox(optional) and/or when the user then clicks the Start CANoe, CANoe program would start with the selected .cfg file.
Am I making any sense here? Or am I doing the right thing here?
Btw, I found these... And I'm using a CANoe library for these, ofc.
#region "***** CANoe Object definition *****"
private CANoe.Application mApp = null; // CANoe Application CANoeƒAƒvƒŠƒP[ƒVƒ‡ƒ“
private CANoe.Measurement mMsr = null; // CANoe Mesurement function CANoe‘ª’è‹#”\
private CANoe.Variable mSysVar = null; // System variable ƒVƒXƒeƒ€•Ï”
private CANoe.Variable mSysVar_start = null; // System variable ƒVƒXƒeƒ€•Ï”
#endregion
I think you have done most of the hard work, unless I've missed something I think you just need something like this in your button1_Click method:
if( textBox1.Text != String.Empty && System.IO.File.Exists(textBox1.Text) )
{
// The textbox has a filename in it, use it
mApp.Open(textBox1.Text, true, true);
}
else
{
// The user hasn't selected a config file, launch with default
mApp.Open("C:\\Users\\uidr3024\\Downloads\\SRLCam4T0_Validation_ControlTool\\cfg\\SVT_SRLCam4T0_025B.cfg", true, true);
}
How can i add the mechanism in my downloader for the case although many threads on SO deals either with php etc and not upto the need.
I have a browse button at the front of a textbox where i get's the user entered Path on local drive to fix the location for downloading but i have already hardcoded one for system drive.I want textbox button to be disabled unless user clciks browse button and then new path can be entered for downloading after then.
How can i go?
A quick example:
private void browseButton_Click(object sender, EventArgs e)
{
var saveFileDialog = new System.Windows.Forms.SaveFileDialog();
var selectedPath= saveFileDialog.ShowDialog();
if (selectedPath == System.Windows.Forms.DialogResult.OK)
{
_savePath = saveFileDialog.FileName;
textBox1.Enabled = true;
textBox1.Text = _savePath;
}
}
I have the following code and am still experiencing a "Dialogs must be user-initiated" exception on the ofd.ShowDialog();
private void btnOpen_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = ALLOWED_FILE_TYPES;
ofd.FilterIndex = 1;
ofd.Multiselect = false;
bool? userClickedOK = ofd.ShowDialog();
if (userClickedOK == true)
{.....}
}
From MSDN:
In addition, there is a limit on the time allowed between when the user initiates the dialog and when the dialog is shown. If the time limit between these actions is exceeded, an exception will occur.
I can't see how the few lines after the click event is taking up this time limit.
Any suggestions on how to avoid this?
Thanks
Ok, have not tested this myself but maybe I found a hint in a quite similar SO question/answer:
private OpenFileDialog OpenFileDialog {get;set;}
public Ctor()
{
OpenFileDialog = new OpenFileDialog();
}
private void btnOpen_Click(object sender, RoutedEventArgs e)
{
...
... OpenFileDialog.ShowDialog();
...
}
Instantiate the dialog in the constructor and only call the ShowDialog method inside your button click handler without instantiating a new dialog.
[Edit]
That's the question/answer I mentioned.
I found the cause of this.
The Loaded event is being subscribed to in the constructor, and while the constructor is called just once for the control, the loaded even is being called twice and hence the btnOpen_Click event is being subscribed to twice.
I can fix it by unsubscribing from the loaded event in the control unloaded event but I'm still not sure why the Loaded is being called twice.