C# open a webpage and see if it was closed - c#

I am trying to keep track of a webpage; whether it was closed, specifically. I use this code to open processes and keep track of close:
this.Process = new Process();
this.Process.EnableRaisingEvents = true;
this.Process.Exited += new EventHandler(Process_Exited);
this.Process.StartInfo.FileName = this.ProcessPath;
this.Process.StartInfo.Arguments = this.Arguments;
this.Process.Start();
private void Process_Exited(object sender, EventArgs e)
{
Console.WriteLine("Exiting...");
}
This works fine for other types of processes, like batch files (it'll print "Exiting..." when I close them). However, if I use it to open a webpage and then close that webpage, it'll never print "Exiting". I assume this is because the browser can have multiple tabs and it's waiting for the whole browser to close. How can I keep track of the specific tab being exited?

Related

Wait until "Write complete"

"simple" question to the "streamer guy's there". My program starts SQL backup processes in single tasks, for any backup per DB.
All the tasks start one by one after the first task finished. But, when the SQL backup command goes to the SQL server, than the process to write the backupfile takes more time then task takes to finish. At this moment, the user can close the program and skip the backupprocess to the big DB files.
Is there a way to block my programm from closing, until every single backupfile is completly written to the HDD?
You can handle the Closing of the Window like this:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (BackupStillRunning)
e.Cancel = true;
else
e.Cancel = false;
}
What you should do though is ask the user if he really wants to quit, something like this:
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (BackupStillRunning)
{
if (MessageBox.Show("The backup is still running, if you close the application, the backup will be cancelled. Do you want to proceed?", "Caption", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
e.Cancel = true;
}
else
{
e.Cancel = false;
}
}
Simply not letting the user close the application will quickly get frustrating. If you really dont want the user to close the application, you should at least show a message explaining why.
As Damien_The_Unbeliever pointed out, there is no way to completely prevent the application from shutting down.

Application stays open due to processes

I'm rather new to C# so I'm not sure if this is even possible...
What I'm trying to do is use an application form to launch other programs via Process, such as Notepad, and then close my original application while Notepad is still running.
Process notePad = new Process();
notePad.StartInfo.FileName = "notepad.exe";
notePad.Start();
Application.Exit();
From what I've found, I have to close/kill the Notepad process in order to close the launching application. I'd like Notepad to remain open, however.
Is there any way to achieve this via C#?
Try this?
using(Process notePad = Process.Start("notepad.exe","")) { }
Application.Exit();
if you want notepad still open after close the form use this code
private void button1_Click(object sender, EventArgs e)
{
Thread notepad_opener = new Thread(opener);
notepad_opener.Start();
}
public void opener()
{
Process.Start("notepad.exe");
Application.Exit();
}
i try this and notepad still open :D
You need to set the UseShellExecute property to True; see this page
You can save the Id of Process you have started:
int id = notePad.Id;
Then Kill it when you want:
Process.GetProcessById(id).Kill();

Opening One word document at a time

I am creating an C# desktop application.
I want to open only one document at a time.
how can i know that already opened word document is closed by the user before i opens next.
The user has to close opened word document.
Any idea or suggestion would be appreciated.
Can you explain how you application is interacting with Word documents? If your application is the only way for a user to open a word document, then once a document is open set a variable:
bDocOpen = true;
Once the document has been closed set it to false. Don't allow opening documents if bDocOpen equals true.
EDIT
You could launch the document and wait for the process to finish. This is not threaded, so your app will be unresponsive until the document is closed. I guess this behavior could be a mechanism to keep multiple documents from being opened. However leaving your app unresponsive is not a good practice, the user will think something is wrong.
bool bDocOpen = false;
private void btnOpenDoc(object sender, EventArgs e)
{
if (!bDocOpen)
{
ProcessStartInfo pInfo = new ProcessStartInfo();
pInfo.FileName = #"C:\temp\word.doc";
Process p = Process.Start(pInfo);
p.WaitForInputIdle();
p.WaitForExit();
//Will not get here till process exits
MessageBox.Show("Document closed");
bDocOpen = false;
}
}

C# OpenFileDialog spawns many threads, and application exit hanging

Lately I have been having problems with my application not shutting down properly. After it has been told to exit, when I look in the Task Manager the process is still running, and I am unable to kill the process.
Suddenly I realized a strange pattern. The shutdown problem only appeared if I had opened a OpenFileDialog anytime when the application was running. I debugged a bit and saw that some threads did not shut down after the application should have exited. Also, to my surprise, when I invoked OpenFileDialog.ShowDialog(), it spawned a lot of threads (See the pictures below). The threads are alive throughtout the lifetime of the application.
Why does OpenFileDialog spawn so many threads? And why are they not closed after the file dialog is closed.
How does the OpenFileDialog problem relate to my shutdown problem...?
Threads just before openFileDialog.ShowDialog():
Threads while the dialog is open:
Threads right after openFileDialog.ShowDialog() has returned:
Threads hanging after the application has been shut down:
Code for opening the dialog:
private void startAllSequenceToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog ofn = new OpenFileDialog();
DialogResult result = ofn.ShowDialog();
if (result == DialogResult.Cancel)
return;
MessageBox.Show("do stuff");
}
I search the web for this and found nothing but I fixed by issue by calling Dispose. Code below:
private void startAllSequenceToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog ofn = new OpenFileDialog();
DialogResult result = ofn.ShowDialog();
if (result == DialogResult.Ok)
{
MessageBox.Show("do stuff");
}
// This one line seems to allow my application to exit cleanly in debug and release.
// But I don't instantiate a new object.
// I used the control on the form and called Dispose from form_closing.
ofn.Dispose();
}
This thread OpenFileDialog/c# slow on any file. better solution? has some half decent answers. All in all, as a last resort check with ProcExp from sysinternals. Also, is it only slow in the debugger? If so I wouldn't worry about it since it doesn't affect your users. Just make sure to isolate from your other code so your team is not constantly tripping over it in the debugger since it is slow.

Run a process for at least 5 seconds in C# WPF

My goal is to force a process to run for at least 5 seconds (any amount of time really). I am working of the .NET Framework 3.5, with Service Pack 1. The idea is that the document holds some information that the user must see, so to safe guard against them immediately clicking to close the document, we can force it to stay open for some time. I developed a small test UI, consisting of a button, and then three radio buttons (one for each document). Here is my code behind...
I define the strings for the file paths, the string for the chosen file's path, and int to store the process's ID, a boolean for if they can exit the program, and the thread and timer declarations such as..
string WordDocPath = #"Some file path\TestDoc_1.docx";
string PowerPointPath = #"Some file path\Test PowerPoint.pptx";
string TextFilePath = #"Some file path\TestText.txt";
string processPath;
int processID;
bool canExit = false;
System.Threading.Thread processThread;
System.Timers.Timer processTimer;
In the constructor, I initialize the thread and timer, setting the thread's start method to a method called TimerKeeper(), and then I start the thread.
processTimer = new System.Timers.Timer();
processThread = new System.Threading.Thread(new System.Threading.ThreadStart(timeKeeper));
processThread.Start();
I have the timer set to count to 5 seconds, upon which it will set the canExit boolean to true.
public void timeKeeper()
{
processTimer.Elapsed += new System.Timers.ElapsedEventHandler(processTimer_Elapsed);
processTimer.AutoReset = false;
processTimer.Interval = 5000; //5000 milliseconds = 5 seconds
}
void processTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
canExit = true;
}
The rest is my button's click event, which deicides which file path to use to start the process, starts the timer, and then starts the process itself..
private void button1_Click(object sender, RoutedEventArgs e)
{
if ((bool)PowerPointRadioButton.IsChecked)
{
processPath = PowerPointPath;
}
if ((bool)WordDocRadioButton.IsChecked)
{
processPath = WordDocPath;
}
if ((bool)TextDocRadioButton.IsChecked)
{
processPath = TextFilePath;
}
try
{
canExit = false;
processTimer.Start();
while (!canExit)
{
processID = System.Diagnostics.Process.Start(processPath).Id;
System.Diagnostics.Process.GetProcessById(processID).WaitForExit();
if (!canExit)
{
processTimer.Stop();
MessageBox.Show("Document must remain open for at least 5 seconds.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
processTimer.Start();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error dealing with the process.\n" + ex.Message.ToString());
}
This actually works, for the most part. The user still can close the document, but if it has not been 5 seconds, it will reopen. Except for the word document (.docx). Things go smoothly for the powerpoint and text files, but the word document has some strange behavior (please note that all 3 files are in the same file directory). When I choose the word documents radio button and click the button, the word document opens, BUT I am also prompted with the message box from the catch block, alerting me that a "Object reference not set to an instance on an object" exception was thrown. This only occurs for the word document. Like I said, the word document still opens (I can see it's contents, just like the powerpoint or textfile). The exception causes the lines that check to see if they can exit to be skipped, so the document can close immediately, which is a problem.
Can anyone see my issue here? Or if there is a better way to doing all of this (I am a wpf/c# newbie)? I just don't understand why this only occurs for the word document, and not the powerpoint and text files.
If this is run on the user's desktop you are subject to the proper app being installed (e.g. Word) and how it is configured. If these are read only files on a share then I could convert them to XPS so you could show them in a DocumentViewer. And rather than force them to wait 5 seconds to click make them say yes to a dialog box that they have read and understand the document. Or have this on a page with an "I agree" button as MilkyWayJoe suggested.
The problem could be that the associated application is not the word application itself, but some intermediate application that launches word on your behalf.
To find out, keep a reference to the process object, and check if it has already terminated, what it's executable path is.
Having said that, why do you need this annoying behavior? You cant stop people from looking the other way. Is it supossed to fullfill some legal requirement or something?

Categories

Resources