Save document immediately after opening program - c#

Please help, I am trying to make program as soon as it opens to prompt with window to save rtf file, I try to use Window_Activated event but when programs starts, it does open window to save as but it doesn't matter if i press on Save or Cancel, the SaveFileDialog keeps showing up in loop and can not get pass that. This is code I used but maybe is not even good.
private void Window_Activated(object sender, EventArgs e)
{
Microsoft.Win32.SaveFileDialog saveDlg = new Microsoft.Win32.SaveFileDialog();
saveDlg.DefaultExt = ".rtf";
saveDlg.Filter = "RTF Documents (.rtf)|*rtf";
Nullable<bool> rezultat = saveDlg.ShowDialog();
if (rezultat == true)
{
string filename = saveDlg.FileName;
System.IO.File.Create(filename);
}
}

Do it like this
*> NOTE: this will used goto statement where other may argued not to
used it but it is still supported and must only be used if no other
options*
private void Window_Load(object sender, EventArgs e)
{
System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog();
saveDlg.DefaultExt = ".rtf";
saveDlg.Filter = "RTF Documents (.rtf)|*rtf";
RetHere:
if (saveDlg.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
{
string filename = saveDlg.FileName;
System.IO.File.Create(filename);
}
else {
System.Windows.Forms.MessageBox.Show("Your message here!", "Save", System.Windows.Forms.MessageBoxButtons.OK);
goto RetHere;
}
}

Window activated occurs when it becomes the foreground window, when you prompt the user to save, it changes focus, on clicking OK or CANCEL it changes back the focus to the main window, firing up the Window_Activated event. Could this be an infinite loop? I didn't test it but I guess it could happen.
Edit: I would suggest yout to use another event, maybe when the form loads?

You can't use Window_Activated for this (clearly). It's fired every time the window is activated. Here's what's happening:
Your app starts.
Window_Activated is executed.
You display the saveDlg, which deactivates your window.
The saveDlg closes, which activates your window.
Go to step #2
You need to either add a flag that is set the first time Window_Activated is executed, and check for it before executing the code, or use a different event that only runs once (like Load).

Related

How to print dialogue ok after delegate?

I have a print dialogue that is triggered from the a button on the binding navigator toolstrip and to give the print dialogue box focus I have created a delegate. My question is how do you trigger the print if dialogue result ok?
This is my code...
delegate DialogResult ShowPrintDialogue();
private void trackPrint_Click(object sender, EventArgs e)
{
PrintDocument docToPrint = new PrintDocument();
trackPrintDialog.AllowSomePages = true;
trackPrintDialog.Document = docToPrint;
docToPrint.DefaultPageSettings.Landscape = true;
docToPrint.DocumentName = "Track";
ShowPrintDialogue spd = new ShowPrintDialogue(trackPrintDialog.ShowDialog);
this.BeginInvoke(spd);
if (spd() == DialogResult.OK) // Doesn't work...
{
docToPrint.PrintPage += new PrintPageEventHandler(PrintImage);
docToPrint.Print();
}
}
I'm not exactly sure why you would want to do this. Calling trackPrintDialog.ShowDialog() should show the print dialog and focus it for user interaction. It should also prevent controls beneath the dialog from being changed.
Calling .BeginInvoke means you're calling an asynchronous section of code, meaning it immediately returns and continues to run the code after it. What that means is that since the user isn't, almost instantaneously, clicking OK on the print dialog, the if-statement evaluates spd() to be None and nothing will print.
The PrintDialog is intended to be blocking, so using a delegate to show and focus the print dialog should not done.

C# - Override the Standard Windows Close Button to Pop-up my Custom Form

Yes, noob question. My apologies.
When users click on the red x button on the window, I want to pop up a message asking if they really would want to quit. I found a similar question on this site: Override standard close (X) button in a Windows Form.
The thing is, I want to customize the font and the MessageBoxIcon for the MessageBox, and sadly it can't be done (or will take a lot of effort to be done). So, I've decided to make my own form.
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (txtID.Text != "" || txtPassword.Text != "")
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown) return;
// Confirm user wants to close
new formConfirmExit().ShowDialog();
}
}
I added this code under the main form. However, when I run my code and I click on the standard close button, my pop up (the custom form I did) doesn't do what it's job. Suppose I click the "No" button, it terminates my entire program. With the "Yes" button, the pop-up shows up again, and then everything kinda stops (on Visual Studio) and ta-da! an exception.
BTW, these are the Yes and No button methods (from my Custom Form's class):
private void btnYes_Click(object sender, EventArgs e)
{
Application.Exit(); // terminate program (exception is in here)
}
private void btnNo_Click(object sender, EventArgs e)
{
this.Close(); // close this pop up window and go back to main window
}
Changing Application.Exit() to Environment.Exit(0) did the job for the Yes button, but my No button, well, terminates the program, still.
Edit: When I click on the Yes button, the pop-up/my custom form shows again (just one time). It'll stay on that state (I can click on the Yes button repeatedly yet nothing happens). The InvalidOperationException is thrown when I click the Yes button first (note the first sentence of this paragraph) then the No button.
Thank you.
Add this in your No_Click:
private void btnNo_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.No;
}
Then, change your forms closing event to the following:
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (txtID.Text != "" || txtPassword.Text != "")
{
base.OnFormClosing(e);
if (e.CloseReason == CloseReason.WindowsShutDown
|| e.CloseReason == CloseReason.ApplicationExitCall)
return;
// Confirm user wants to close
using(var closeForm = new formConfirmExit())
{
var result = closeForm.ShowDialog();
if (result == DialogResult.No)
e.Cancel = true;
}
}
}
First, it checks if the form isn't closing through Application.Exit(), this may be triggered from your other form, so it will not reshow the custom MessageBox.
Second, you create a using statement around your custom form. This way you can preserve the values. You then set the dialogresult to no, if the user doesn't want to cancel. If this is the case, set e.Cancel = true to stop from exiting.

UI not getting updated after call to OpenFileDialog.ShowDialog()

I have a WPF Application consisting of a MainWindow which also has a regular button inside.
Bound to the button click event I am loading a serialized object via OpenFileDialog:
private void LoadNetwork_Click(object sender, RoutedEventArgs e)
{
var openDialog = new OpenFileDialog { Multiselect = false };
var result = openDialog.ShowDialog();
if (result)
{
string file = openDialog.FileName;
try
{
_network= new SimplifiedNetwork(file, 1);
MessageBox.Show("Loaded OK");
}
catch (Exception)
{
MessageBox.Show("Load error");
}
}
}
After this method gets executed the UI doesn't update anymore. And when I say nothing, I mean not even the hover effects on the buttons in the Window work (not to mention updating labels via code behind, property changed events, begin invokes etc.), it's like it's frozen (but still responsive to clicks).
I thought it was something I did inside my routines, but simply reducing the method call to
private void LoadNetwork_Click(object sender, RoutedEventArgs e)
{
var openDialog = new OpenFileDialog { Multiselect = false };
var result = openDialog.ShowDialog();
}
has the same result.
Clarification.
-This occurs with after the Modal dialog is closed.
-It also seems to manifest itself as soon as the UI loses focus for any reason (like minimize - restore, switch to another window).
-This seems to occur only on my Windows 8.1 machine (put in an xp VM I have around, is OK).
Any ideas?
The OpenFileDialog is a modal dialog, it is intended that the window in the background is not responding when the dialog is open.
Here is more information and also a possible solution to your problem.

Why isnt my windows form closing?

Im playing about with some very simple windows forms. I have an event handler for a form close event that asks the user whether they want to save what they've typed:
private void closeNpForm(object sender, FormClosingEventArgs e)
{
if (!saveFlag)
{
if (MessageBox.Show("Do you want to save the text entered?", "Save Changes?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
e.Cancel = true;
saveFlag = true;
writeToFile(this.allText.Text);
}
}
}
if the user clicks yes (indicating they do want to save their text) i call the writeToFile method, and also set a flag so as not to ask them to save again:
private void writeToFile(string text)
{
writer = new StreamWriter("inputdata.txt");
writer.Write(text);
writer.Close();
this.Close();
}
As far as i can see, the writeToFile method should close the form when its finished. But this isnt happening, when i run the writeToFile method, the form just stays open. Can anyone tell me what im doing wrong?
as i understand it, calling this.Close() should trigger a form closing event, calling my event handler, due to the flag now being true, the form should just close without a problem.
note, my parent class extends the Form class, so im just using this to refer to my form instance.
e.Cancel = true -- whoops. The event is told cancel (read: not close the window).
I suspect that because close() is being called from within the close event and there is some internal clobbering going on (either suppressed or the Cancel is propagated over, etc). Just clean up the code (saving to the file has nothing to do with closing the window although the file might be saved and the window closed from within a button event.)
Happy coding.
writing to file and closing the form are two different kinds of operations. you should not have this.Close() in your writeToFile method.
As pst says, by setting e.cancel to true, you are basically telling the CloseForm event to be cancelled, therefore it's not closing once it exits from the closeNpForm event handler.
After exiting closeNpForm, the form checks for the Cancel property of the event and will not actually proceed with closing itself.
Why are you cancelling the close event and then calling writeToFile that closes the form?
In addition to what #pst said, why are you setting Cancel = true if you don't want to cancel the closing of the form?
If you remove e.Cancel = true; and this.Close(); it should do what you want.
This works for me:
public class Form1 : Form
{
bool saveFlag;
private void Form1_Load(object sender, EventArgs ev)
{ FormClosing += closeNpForm;
}
private void closeNpForm(object sender, FormClosingEventArgs e)
{
if (!saveFlag)
{
if (MessageBox.Show("Do you want to save the text entered?", "Save Changes?", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
e.Cancel = true;
saveFlag = true;
this.Close();
}
}
}
}

When to make a form flash and stop flashing?

I am writing an IM program, and I have the method to make a form flash and stop flashing... question is, how do I implement it?
When a message arrives, I can set the window flashing, but I need to make sure it doesn't have focus. Checking the focued method always seems to return false and so it flashes even when the form is open.
Also, which event to I need to handle to stop it flashing? When the user clicks the form to make it maximise, or switches focus to the form, I need a way of stopping it.
What's the best way?
You can handle the Activated and Deactivate events of your Form, and use them to change a Form-level boolean that will tell your code whether your form has the focus or not, like this:
private bool _IsActivated = false;
private void Form1_Activated(object sender, EventArgs e)
{
_IsActivated = true;
// turn off flashing, if necessary
}
private void Form1_Deactivate(object sender, EventArgs e)
{
_IsActivated = false;
}
When a message arrives, you check _IsActivated to determine if your Form is already the active window, and turn on flashing if it isn't. In the Activated event, you would turn off the flashing if it's on.
The Focused property of your form will always return false if it has any controls on it. This property refers to whether the control in question (the form, in this case) has the focus within your application's form, not whether the application itself has the focus within Windows.
Checking if the form is minimized or not:
if (this.WindowState == FormWindowState.Minimized)
{
MakeFormFlash();
}
else
{
MakeFormStopFlash();
}
Event to trigger when the form is activated by user or code:
this.Activated += new EventHandler(Form_Activated);
Well Focused should be the property to check, so you need to try and work out why that is always returning false.
As for what event to listen to, probably the GotFocus event, though that may not work until you can work out what is wrong with the Focused property.
There are a number of ways you can handle this. Probably the easiest would be to have a flag that you set whenever the form is flashing so this can be reset on re-activation of the form e.g.
Code for base IM window form
private bool IsFlashing;
....
// Code for IM windows
public void OnActivate(EventArgs e)
{
if (IsFlashing)
{
// stop flash
IsFlashing = false;
}
}
public void Flash()
{
// make flash
IsFlashing = true;
}
Then wherever you do your code to handle the new message you would just need to check that the particular conversation window (if you handle multiple ones) that the message is directed at is the current active one:
public void OnNewMessage(AMessage msg)
{
Form convoWindow = FindConvoWindow(msg.Sender);
if (Form.ActiveForm == convoWindow)
{
// update the conversation text
}
else
{
convoWindow.Flash();
}
}

Categories

Resources