It is a small part of my program where my program needs to start the program from DataGridView (Content Clicked Event) and its just executing that program perfectly but is not able to close it because some of incoming programs don't have same process name as file name. I tried getting processid too but it throws following error (can you please provide me a working code because i can get the id of my winform process but how can i get the processid of externally launched app from my program.
i tried it it throws the following error
An unhandled exception of type 'System.ArgumentException' occurred in System.dll
Additional information: Process with an Id of 16924 is not running.)"
the code in which i am getting process id but fails is below
private void button1_Click(object sender, EventArgs e)
{
var processid = Process.Start("Calc");
pn =processid.ProcessName;
pid = processid.Id;
}
int pid;
String pn;
private void button2_Click(object sender, EventArgs e)
{
var process1 = Process.GetProcessById(pid);
process1.Kill();
}
The dummy code is below.
I have already tried:
private void button1_Click(object sender, EventArgs e)
{
Process.Start("Calc");
}
private void button2_Click(object sender, EventArgs e)
{
foreach (var process in Process.GetProcessesByName("Calc"))
{
process.Kill();
}
}
My Code:
private void button1_Click(object sender, EventArgs e)
{
Process.Start("THIS PATH WILL COME FROM DATABASE");
}
private void button2_Click(object sender, EventArgs e)
{
foreach (var process in Process.GetProcessesByName("PROCESS NAME WHICH MY PROGRAM STARTED"))
{
process.Kill();
}
}
When you start the process get the Id of the process, and store it. You can then get the process by id to kill it. This not only ensures you don't need to know the name of the process (in case it's different from the path to start it) but ensures that you kill the correct instance if there are multiple instances running, some of which weren't started by your program.
Related
What I'm trying to do is get user input from a form (IncomeForm) by using a textbox (TextBoxIncomePrice) and after pressing the button (ButtonConfirmIncome), the LabelIncome label in the form MainPage should change to the value input by the user.
Everything works as intented, except for when I try to reopen the IncomeForm by clicking the AddIncomeButton. I get the error shown in the title. It should be able to reopen and accept a new value no matter how many times you close the IncomeForm.
Main Form (MainPage):
IncomeForm incomeForm = new IncomeForm();
private void incomeForm_FormClosed(object sender, FormClosedEventArgs e)
{
LabelIncome.Text = incomeForm.TextBoxIncomePrice.Text;
}
private void AddIncomeButton_Click(object sender, EventArgs e)
{
incomeForm.FormClosed += new FormClosedEventHandler(incomeForm_FormClosed);
incomeForm.Show();
}
Add Income Form (IncomeForm):
private void ButtonConfirmIncome_Click(object sender, EventArgs e)
{
this.Close();
}
I'm in process of learning C# and WPF specifically. I have a program currently written but it's having an issue closing. When a user closes the main window, the program ends, but the process continues running in the background. Each time a new window is open, a new process is created and never ends. I attempted to fix this by adding the following code to my MainWindow.xaml.cs file:
private void InventoryUpdater_Closed(object sender, EventArgs e)
{
Application.Current.Shutdown();
}
This closes the process but causes a window to pop up that acts like the program shutdown incorrectly and prompting the user to "Close the program". That window states, "[Application Name] has stopped working.
How can I end my application process without it prompting the user each time they want to close? Is it possible I've not properly disposed something?
So I figured out what was causing the prompt and what was causing the unending process.
The prompt had to do with my opening and closing of the other 3 windows. Here is what I changed to stop getting the error from Application.Current.Shutdown(). I changed this code:
private void settingsWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
updateSettings();
e.Cancel = true;
main.Show();
Hide();
}
private void settingsButton_MouseUp(object sender, RoutedEventArgs e)
{
settingsWindow settingsWindow = new settingsWindow(this);
if (!settingsWindow.settingsOpen)
{
settingsWindow.Show();
Hide();
}
}
To this code:
private void settingsWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
updateSettings();
}
private void settingsButton_MouseUp(object sender, RoutedEventArgs e)
{
settingsWindow settingsWindow = new settingsWindow(this);
if (!settingsWindow.settingsOpen)
{
settingsWindow.ShowDialog();
}
}
Once I close main it was going back through the other window instances that I had initialized on load and was cycling through their Closing events. Once it was getting to main.Show(), it was failing to Show something that had already been closed.
Once I did that, I was about to figure out that the original initializing of the additional windows in my Loaded event was causing the additional trace backs that weren't ending. Here is what I changed. I changed this:
private void InventoryUpdater_Loaded(object sender, RoutedEventArgs e)
{
settingsWindow settings = new settingsWindow(this);
sftpSettings severSettings = new sftpSettings(settings);
TimeSpan na = queueCustomTask();
Stop = true;
runManually.IsEnabled = true;
ssdRunManually.IsEnabled = true;
startAutoRun.IsEnabled = true;
}
To this:
private void InventoryUpdater_Loaded(object sender, RoutedEventArgs e)
{
TimeSpan na = queueCustomTask();
Stop = true;
runManually.IsEnabled = true;
ssdRunManually.IsEnabled = true;
startAutoRun.IsEnabled = true;
}
I'm not even sure why the initializing was still there. Everything had been switched to static global variables so removing those two lines affected nothing. Thanks for all the shoves in the right direction!
I have a project that reads content from web and saves it to the database.
I use Timer control to wait for ajax changes and it has been working for a long time without any problem.
But unexpectedly it is not working any more. I get the following error :
Exception thrown: 'System.Runtime.InteropServices.COMException' in
SnapshotInfo.exe
Additional information: Error HRESULT E_FAIL has been returned from a
call to a COM component.
Part of the code on this problem :
WebBrowser _browser = new WebBrowser();
private void Form1_Load(object sender, EventArgs e)
{
_browser.Dock = DockStyle.Fill;
_browser.DocumentCompleted += _browser_DocumentCompleted;
Controls.Add(_browser);
}
private void _browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (!timer1.Enabled)
{
// do any thing
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_browser.Dispose();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_browser.Document==null || _browser.Document.Body==null) return;
var body = _browser.Document.Body.InnerHtml; // ----> error here
if (body.Contains("word"))
{
// code when word is exist
timer1.Enabled = false;
}
}
private void button1_Click(object sender, EventArgs e)
{
_browser.Navigate(textBox1.Text);
timer1.Enabled = true;
}
I do not know where is the problem?
Thanks for any help
Make sure you are using latest version of web browser control , check below link
Use latest version of Internet Explorer in the webbrowser control
or you can replace web browser control with another web browser engine like http://www.awesomium.com/ it's free and easier to use
The problem solved by deleting the security update KB3087040!
What my code basically does is it allows the user to browse for a folder that has a bunch of files, and when the user clicks a "Start" button, a code that makes files with the same name and different extensions for the ones in the folder runs. What I want to do is add a cancel button so if the user clicks the start button on a folder that was the incorrect one for example, the user can cancel out, browse to the correct folder, and restart the operation.
This is the code that fires when the start button is clicked:
class ExcelCode
{
public static void DoExcel (string FolderPath)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(FolderPath + ".fdf");
Thread.Sleep(1000);
}
}
What I tried so far after hours upon hours of researching was to have the backgroundworker.CancelAsync(); called on the Cancel button, and a global variable that keeps track of the cancellation, ie. the DoWork() method looks like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if(backgroundWorker1.IsBusy)
for (int i = 0; i < 100; i++)
{
foreach (string file in filePaths)
{
if(backgroundWorker1.CancellationPending)
{
e.Cancel = true;
restartWorker = true;
return;
}
ExcelCode.DoExcel(file);
//write to textbox
}
backgroundWorker1.ReportProgress(i);
}
}
And my RunWorkerComplete method looks like this:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled && restartWorker)
{
if (backgroundWorker1.IsBusy)
{
restartWorker = true;
backgroundWorker1.CancelAsync();
return;
}
MessageBox.Show("Worker has cancelled");
restartWorker = false;
return;
}
}
Start Button:
private void button1_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy)
{
restartWorker = true;
backgroundWorker1.CancelAsync();
}
else
{
backgroundWorker1.RunWorkerAsync();
}
button2.Enabled = true;
}
Cancel Button:
private void button2_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
Now this all works well for cancelling out just once, when I try to start again on a different folder I get this error:
An exception of type 'System.IO.IOException' occurred in mscorlib.dll but was not handled in user code
Additional information: The process cannot access the file 'C:\Users\Pierre\Desktop\Test Folder - Copy\New Text Document - Copy - Copy - Copy - Copy - Copy (8).txt.fdf' because it is being used by another process.
The code has everything I researched on so it should pretty much show my entire progress on this. Any guidance as to what should be done is greatly appreciated.
EDIT: The code actually works for the second folder, that is it generates the file but throws the exception anyway.
You are not explicitly releasing the StreamWriter object, so it will only be released when GC kicks off on the object and releases the file. To avoid this issue, change your DoExcel method as follows:
public static void DoExcel (string FolderPath)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(FolderPath + ".fdf"))
{
Thread.Sleep(1000);
file.Close();
}
}
i'm having trouble finding enough resources to create the windows form application that i want.As title says i want to create an application on which i can set a timer to shutdown computer.Any example or help would be appreciated.Regards
Edit:so i've mananged to put current date/time button and individual shutdown button the problem is i dont know how to set a timer on shutdown during the program is running.
Heres what i've put so far:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonTimerStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
labelDate.Text = DateTime.Now.ToString();
}
private void buttonTimerStop_Click(object sender, EventArgs e)
{
timer1.Stop();
}
private void buttonShutdown_Click(object sender, EventArgs e)
{
Process.Start("Shutdown", "-s -t 0");
}
Basically one way to do it is to execute the windows shutdown executable and pass to it whatever timer parameters you want from your C# program. To execute any external program including this one from within your C# program you'll have to create a process, assign an executable to that process and start it something like this:
string path = #" C:\Windows\System32";
string shut_args = " ";
process1.StartInfo.FileName = " shutdown.exe";
process1.Start();
Here is a very detailed tutorial that shows exactly what you want to do: http://www.codeproject.com/Articles/22718/Shutdown-Remote-Using-Shutdown-exe
I think this can help :
How to shut down the computer from C#
Process.Start("shutdown","/s /t 0");
For the timing use the Windows form 'Timer'