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)
{
....
}
}
}
....
....
}
Morning all,
I have a c# app where if you press a start button a dialog box will open and the OK button will be automatically pressed. The problem is I don't know how to do this.
The code is below:
private void Start_Click(object sender, EventArgs e)
{
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
var videoSource = captureDevice.VideoDevice;
FinalVideo = captureDevice.VideoDevice;
FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
FinalVideo.Start();
}
}
I have tried:
Removing the if statement to directly run whats inside it
Put DialogResult.OK = true before the if statement
CaptureDevice.DialogResult.OK = true before the if statement;
Image shows the dialogbox when start is pressed
This dialog let you select the source capturing device. If you want to bypass this dialog you should specify source device in your code. if you use AForge.Net this link help you. if not search for appropriate solution in documentation of component or library you use.
Add a new button to your form. Call it "Settings". In the event handler for this button, you roughly put the first half of what you have now for the Start button. Create a Settings object in your MainForm in which you will store the camera chosen.
private void Settings_Click(object sender, EventArgs e)
{
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
settings.VideoSource = captureDevice.VideoDevice;
}
}
private void Start_Click(object sender, EventArgs e)
{
FinalVideo = settings.VideoSource;
FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
FinalVideo.Start();
}
Hope this helps.
I have sort of found a solution to the question and it was to use:
SendKeys.Send("{ENTER}");
I used it before the if statement and it works with the Start_Click method but when i use it in a method called Start_Vid(), I get the error:
'SendKeys cannot run inside this application because the application is not handling Windows messages. Either change the application to handle messages, or use the SendKeys.SendWait method'
I have no idea why it should not work and what the error message means so should I be creating another question to have this answered or can it be solved in here do you think?
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.
There are many questions on SO asking same doubt.
Solution for this is to set
notifyIcon.icon = null and calling Dispose for it in FormClosing event.
In my application, there is no such form but has Notification icon which updates on Events.
On creation, I hide my form and make ShowInTaskbar property false. Hence I can not have a "FormClosing" or "FormClosed" events.
If this application gets event to exit, It calls Process.GetCurrentProcess().Kill(); to exit.
I have added notifyIcon.icon = null as well as Dispose before killing, but still icon remains taskbar until I hover mouse over it.
EDIT: If I assume that this behaviour is due to calling GetCurrentProcess().Kill(), Is there any elegant way to exit from application which will clear all resources and remove icon from system tray.
You can either set
notifyIcon1.Visible = false;
OR
notifyIcon.Icon = null;
in the form closing event.
The only solution that worked for me was to use the Closed event and hide and dispose of the icon.
icon.BalloonTipClosed += (sender, e) => {
var thisIcon = (NotifyIcon)sender;
thisIcon.Visible = false;
thisIcon.Dispose();
};
Components just must be disposed in the right order like this :
NotifyIcon.Icon.Dispose();
NotifyIcon.Dispose();
Add this to the MainWindow closing event.
Hope this will help.
Use this code when you want to do it when you press the Exit or Close button:
private void ExitButton_Click(object sender, EventArgs e)
{
notifyIcon.Dispose();
Application.Exit(); // or this.Close();
}
Use this code when you want to do it when the form is closing:
private void Form1_FormClosing(object sender, EventArgs e)
{
notifyIcon.Dispose();
Application.Exit(); // or this.Close();
}
The important code is this:
notifyIcon.Dispose();
Use notifyIcon.Visible = False in FormClosing event
This is normal behaviour, unfortunately; it's due to the way Windows works. You can'r really do anything about it.
See Issue with NotifyIcon not dissappearing on Winforms App for some suggestions, but none of them ever worked for me.
Also see Notify Icon stays in System Tray on Application Close
Microsoft have marked this as "won't fix" on Microsoft Connect.
The only way that works to me was:
On design screen changing notifyicon1 property visible=false
Insert the code below on main form "activated" event:
NotifyIcon1.Visible = True
Insert the code below on main form "closing" event:
NotifyIcon1.Visible = false
NotifyIcon1.Icon.Dispose()
NotifyIcon1.Dispose()
I don't think WPF has it's own NotifyIcon, does it? If you're using the 3rd party Harcodet.Wpf.TaskbarNotification, then try this:
In order to prevent my app from closing when the window is closed (run in background), I separated the logic for closing the window (hitting the x button in the upper right) and actually shutting it down (through the context menu). To make this work, make your context menu set _isExplicitClose to true. Otherwise, it'll just hide the window and continue to run.
What this does is, on explicit close, hide tray icon and the form before closing. This way the icon isn't hanging around after the application is shutdown.
private bool _isExplicitClose;
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
if (!_isExplicitClose)
{
e.Cancel = true;
Hide();
}
}
protected void QuitService(object sender, RoutedEventArgs e)
{
_isExplicitClose = true;
TaskbarIcon.Visibility = Visibility.Hidden;
Close();
}
Try Application.DoEvents(); after setting notifyIcon.Icon to null and disposing:
notifyIcon.Icon = null;
notifyIcon.Dispose();
Application.DoEvents();
And consider Environment.Exit(0); instead of Process.GetCurrentProcess().Kill().
i can tell you can solve the problem simply using the .dispose() method, but that is not called if you kill the process instead of exit the application.
please refer to Application.Exit if you have built a simple Windows Form application else refer to Environment.Exit that is more general.
I tried all of these and none of them worked for me. After thinking about it for a while I realized that the application creating the "balloon" was exiting before it had a chance to actually dispose of the balloon. I added a while loop just before Application.Exit() containing an Application.DoEvents() command. This allowed my NotifyIcon1_BalloonTipClosed to actually finish disposing of the icon before exiting.
while (notifyIcon1.Visible)
{
Application.DoEvents();
}
Application.Exit();
And the tip closed method: (You need to include the thisIcon.visible = false in order for this to work)
private void NotifyIcon1_BalloonTipClosed(object sender, EventArgs e)
{
var thisIcon = (NotifyIcon)sender;
thisIcon.Icon = null;
thisIcon.Visible = false;
thisIcon.Dispose();
}
I had the exact same problem as you.
The proper way are send WM_CLOSE message to a process.
I use the c# code I found in this article.
http://social.msdn.microsoft.com/Forums/vstudio/en-US/82992842-80eb-43c8-a9e6-0a6a1d19b00f/terminating-a-process-in-a-friendly-way
edit codes of ...Designer.cs as below coding.
protected override void Dispose(bool disposing)
{
if (disposing )
{
this.notifyicon.Dispose();
}
base.Dispose(disposing);
}
I couldn't make any one of the other solutions work. It turned out to be kind of a hybrid of all the above! I hunted and pecked until I had a consistently working solution both in debug and in EXE execution modes! I have no idea why MSFT would mark this as "Not going to fix"? I wish I had that liberty!
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
//THIS CODE IS CRAZY BUT MUST BE DONE IN ORDER TO PROPERLY REMOVE THE SYSTEM TRAY ICON!
//GREAT ARTICLE ON THIS ON STACK OVERFLOW
//https://stackoverflow.com/questions/14723843/notifyicon-remains-in-tray-even-after-application-closing-but-disappears-on-mous
//BTW THIS IS KIND OF A BLEND OF ALL THE SOLUTIONS BECAUSE I COULD NOT FIND A SINGLE SOLUTION THAT WOULD WORK!
systray_icon.Visible = false;
while (systray_icon.Visible)
{
Application.DoEvents();
}
systray_icon.Icon.Dispose();
systray_icon.Dispose();
Environment.Exit(1);
}
The right answer has already been given. But you must also provide a delay, for example with a timer. Only then the application can still remove the icon in the background.
private System.Windows.Forms.Timer mCloseAppTimer;
private void ExitButton_Click(object sender, EventArgs e)
{
notifyIcon.Visible = false; notifyIcon.Dispose;
mCloseAppTimer = new System.Windows.Forms.Timer();
mCloseAppTimer.Interval = 100;
mCloseAppTimer.Tick += new EventHandler(OnCloseAppTimerTick);
}
private void OnCloseAppTimerTick(object sender, EventArgs e)
{
Environment.Exit(0); // other exit codes are also possible
}
I cannot close one of my forms programmatically. Can someone help me?
Here's the code:
private void WriteCheck_Load(object sender, EventArgs e) {
SelectBankAccountDialog sbad = new SelectBankAccountDialog();
DialogResult result = sbad.ShowDialog();
if (result == DialogResult.Cancel) {
this.Close();
} else {
MessageBox.Show(result.ToString());
}
MessageBox.Show(sbad.bankaccountID.ToString());
}
As configurator mentioned (in comments), the form must be shown before it can be closed, so, instead of the Load event, you should be doing this in the Shown event instead.
If you don't want the form visible for the Dialog box, I guess you can wrap the event code in a Visible = false;
In summary, the basic code would be
private void WriteCheck_Shown(object sender, EventArgs e)
{
Visible = false;
SelectBankAccountDialog sbad = new SelectBankAccountDialog();
DialogResult result = sbad.ShowDialog();
if (result == DialogResult.Cancel) {
this.Close();
} else {
MessageBox.Show(result.ToString());
}
MessageBox.Show(sbad.bankaccountID.ToString());
Visible = true;
}
By calling Form.Close(), the form should close, but not until all waiting events have been processed. You also still have a chance to cancel the form closing in the FormClosing event.
First, you'll probably want to return after your call to this.Close(). If it still doesn't close, step through your code and see what is happening. You may have to set and check a "forciblyClose" flag and return from any other processing methods before it'll actually close.
The actual problem is that windows won't let a form close on it's load method. I have to show the dialog on construction, and then if the dialog result is cancel I have to throw an exception and catch the exception on form creation.
This place talks more about it