I'd like to know how to exit my opened Application properly.
The way I am currently trying is not working.
This is how I am opening the application:
private void button1_Click(object sender, EventArgs e)
{
if (status != true)
{
status = true;
// Start a process to print a file and raise an event when done.
myProcess.StartInfo.FileName = "C:\\Users\\David\\Desktop\\Test\\Test.exe";
myProcess.Exited += new EventHandler(Process_Exited);
myProcess.EnableRaisingEvents = true;
myProcess.Start();
}
}
private void button2_Click(object sender, EventArgs e)
{
myProcess.Close();
status = false;
}
I've managed to do it, just do:
myProcess.Kill();
Related
Long Story Short,
The app I am making will Launch a Game.
The Start button will then Check to make sure the games EXE is running..
IF it is running, it will run a script to press buttons 1, 2, and 3..
After that it will loop that script, but first checking if the game has not crashed (if it crashed it wont run the loop)
My Issue:
While the loop is running, which is using System.Threading.Thread.Sleep,
does not let other functions of the app preform (in this case showing and hiding button, and changing label colors.) The main reason this is important is the button it wont is the Stop button which is suppose to end the looping script.
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
Timer timer;
Stopwatch sw;
public Form1()
{
InitializeComponent();
button4.Visible = false;
button2.Enabled = false;
}
private void timer_Tick(object sender, EventArgs e)
{
label2.Text = sw.Elapsed.Seconds.ToString() + "seconds";
Application.DoEvents();
}
// ===============================================
// BUTTON FUNCTIONS
// ===============================================
// Launch GAME
private void button1_Click(object sender, EventArgs e)
{
// Launch GAME
Process.Start(#"C:\Windows\System32\Notepad.exe");
button2.Enabled = true;
}
// START BOT
private void button2_Click(object sender, EventArgs e)
{
status.Text = #"Starting Bot..";
timer = new Timer();
timer.Interval = (1000);
timer.Tick += new EventHandler(timer_Tick);
sw = new Stopwatch();
timer.Start();
sw.Start();
BotReady(sender, e);
}
// PLAYER DIED
private void button3_Click(object sender, EventArgs e)
{
KillBot(sender, e);
status.Text = #"lol u ded";
}
// STOP THE BOT
private void button4_Click(object sender, EventArgs e)
{
KillBot(sender, e);
status.Text = #"Bot Stopped";
button2.Visible = true;
button4.Visible = false;
button2.Enabled = true;
}
// KILL GAME AND BOT (IF IT CRASHED OR SOMETHING)
private void button5_Click(object sender, EventArgs e)
{
}
// ===============================================
// OTHER FUNCTIONS
// ===============================================
// Target GAME application
private void TargetAQ(object sender, EventArgs e)
{
// this part doesnt work yet.
// Selection.Application and Tab to it
}
// CHECK IF GAME IS STILL RUNNING, KILL BOT IF GAME IS NOT DETECTED
public void CheckStatus(object sender, EventArgs e)
{
Process[] GAME = Process.GetProcessesByName("notepad");
if (GAME.Length == 0)
// GAME NOT running
{
KillBot(sender, e);
button2.Enabled = false;
status.Text = #"GAME is not Running, Bot Stopped.";
uGAME.ForeColor = Color.Red;
button2.Visible = true;
button4.Visible = false;
button2.Enabled = false;
}
else
// GAME IS running
{
status.Text = #"GAME is Running!";
uGAME.ForeColor = Color.Green;
button2.Visible = false;
button4.Visible = true;
}
}
// Verify bot and GAME are running before starting
public void BotReady(object sender, EventArgs e)
{
CheckStatus(sender, e);
if (uGAME.ForeColor == Color.Green)
{
status.Text = #"Bot Started!";
Botting(sender, e);
}
else { status.Text = #"GAME is not running"; }
}
//THE BOT ACTIONS
public void Botting(object sender, EventArgs e)
{
// Check to make sure everything is still running
CheckStatus(sender, e);
TargetAQ(sender, e);
if (uGAME.ForeColor == Color.Green)
{
// all is running, then you good.
Script(sender, e);
}
//GAME died, kill scripts
else {
KillBot(sender, e);
status.Text = #"GAME Crashed:(";
}
}
//Things it does in-game
public void Script(object sender, EventArgs e)
{
status.Text = #"Bot in progress..";
// Use skills in game rotation
System.Threading.Thread.Sleep(3000);
SendKeys.Send("1");
System.Threading.Thread.Sleep(3000);
SendKeys.Send("2");
System.Threading.Thread.Sleep(3000);
SendKeys.Send("3");
// Go back and check the game has not crashed before re-running the script
Botting(sender, e);
}
// STOP THE BOT AND TIME COUNTER
public void KillBot(object sender, EventArgs e)
{
// kill the clock and bot
status.Text = #"Stopping bot...";
timer.Stop();
sw.Stop();
label2.Text = sw.Elapsed.Seconds.ToString() + " seconds";
status.Text = #"Bot Stopped";
}
}
}
I have this code:
private void btnAddDataToCSV_Click(object sender, EventArgs e)
{
var myProcess = new Process();
this.Enabled = false;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(Excel_Exit);
myProcess.StartInfo.FileName = "D:\\MyCsvFile.csv";
myProcess.Start();
}
public void Excel_Exit(object sender, System.EventArgs e)
{
MessageBox.Show("Success!!");
this.Enabled = true;
}
The code works as far as graying out all the buttons on my C# user form and opening the csv file in Excel. When I close Excel the exit event fires displaying a message "Success!!" But it doesn't re-enable the buttons after closing Excel.
I am getting the error
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
on the this.Enabled = true; line.
As you can see from my comments below. I have now come to to realization that I cannot figure out how to disable even a single button.
private void btnAddDataToCSV_Click(object sender, EventArgs e)
{
var myProcess = new Process();
button1.Enabled = false;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(Excel_Exit);
myProcess.StartInfo.FileName = "D:\\MyCsvFile.csv";
myProcess.Start();
}
public void Excel_Exit(object sender, System.EventArgs e)
{
button1.Enabled = true;
}
The event is firing because the code below works... (displays success!!)
private void btnAddDataToCSV_Click(object sender, EventArgs e)
{
var myProcess = new Process();
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(Excel_Exit);
myProcess.StartInfo.FileName = "D:\\MyCsvFile.csv";
myProcess.Start();
}
public void Excel_Exit(object sender, System.EventArgs e)
{
MessageBox.Show("Success!!");
}
Any help would be greatly appreciated.
i have added 2 more controls to the form, and set it to disabled on opening of excel file.
private void btnAddDataToCSV_Click(object sender, EventArgs e)
{
var myProcess = new Process();
AddtoCsv.Enabled = false;
textBox1.Enabled = false;
checkBox1.Enabled = false;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(Excel_Exit);
myProcess.StartInfo.FileName = "E:\\MyCsvFile.csv";
myProcess.Start();
}
after that, fetched all the controls inside our form and pass it to SetButtonState method.
public void Excel_Exit(object sender, System.EventArgs e)
{
// Set Button Enable State True
var controls = this.Controls.Cast<Control>();
foreach (Control ctrl in controls)
{
SetButtonState(ctrl);
}
}
SetButtonState wil make call to invoke method of passed control and then we are able to make changes onto control.
private delegate void SafeCallDelegate(Control control);
private void SetButtonState(Control control)
{
// check if current thread is same which have created this control
if (control.InvokeRequired)
{
SafeCallDelegate d = new SafeCallDelegate(SetButtonState);
control.Invoke(d, control);
}
else
{
control.Enabled = true;
}
}
Replace this.Enabled = false; with AddtoCsv.Enabled = false;
private void btnAddDataToCSV_Click(object sender, EventArgs e)
{
var myProcess = new Process();
AddtoCsv.Enabled = false;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(Excel_Exit);
myProcess.StartInfo.FileName = "E:\\MyCsvFile.csv";
myProcess.Start();
}
Just call SetButtonStatemethod inside your Excel_Exit method, and do not forget to declare the delegate.
public void Excel_Exit(object sender, System.EventArgs e)
{
// Set Button Enable State True
SetButtonState();
}
private delegate void SafeCallDelegate();
private void SetButtonState()
{
// check if current thread is same which have created this control
if (AddtoCsv.InvokeRequired)
{
SafeCallDelegate d = new SafeCallDelegate(SetButtonState);
AddtoCsv.Invoke(d);
}
else
{
AddtoCsv.Enabled = true;
}
}
Ok... I couldn't get the entire form to disable. But based on other stuff I have found, I created a "panel" and put all my buttons inside the panel and was able to enable the entire panel.
So the solution below works. Special thanks to Paramjot Singh who posted the other solution which works great for a single button, I don't know if I would have figured this out without his help!!
private void btnAddDataToCSV_Click(object sender, EventArgs e)
{
var myProcess = new Process();
panel1.Enabled = false;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(Excel_Exit);
myProcess.StartInfo.FileName = "E:\\MyCsvFile.csv";
myProcess.Start();
}
public void Excel_Exit(object sender, System.EventArgs e)
{
// Set Button Enable State True
SetButtonState();
}
private delegate void SafeCallDelegate();
private void SetButtonState()
{
// check if current thread is same which have created this control
if (panel1.InvokeRequired)
{
SafeCallDelegate d = new SafeCallDelegate(SetButtonState);
panel1.Invoke(d);
}
else
{
panel1.Enabled = true;
}
}
so I have this code
public void Update_Click(object sender, EventArgs e)
{
using (PccBiometricsHandler.Form1 ShowProgress = new PccBiometricsHandler.Form1())
{
menu.Items[2].Enabled = false;
ShowProgress.ShowDialog();
ShowProgress.FormClosed += new FormClosedEventHandler(MyForm_FormClosed);
}
}
public void MyForm_FormClosed(object sender, FormClosedEventArgs e)
{
updaterAccess();
menu.Items[2].Enabled = true;
}
so after I click Update it will run the child form Form1
which is this:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
notifyIcon1.Visible = true;
notifyIcon1.BalloonTipTitle = "Update Complete";
notifyIcon1.BalloonTipText = "Successfully Update";
notifyIcon1.ShowBalloonTip(500);
timer1.Interval = 4000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
notifyIcon1.Dispose();
this.Close();
}
so as you can see it runs on a backgroundworker with a timer to close the child Form1
now my problem is that after closing the Child Form1 it doesn't run the MyForm_FormClosed which it should enable menu.Items[2] again and updaterAccess()
I think I'm missing something in my mainForm
Attached the event handler before firing ShowDialog
public void Update_Click(object sender, EventArgs e)
{
using (PccBiometricsHandler.Form1 ShowProgress = new PccBiometricsHandler.Form1())
{
menu.Items[2].Enabled = false;
ShowProgress.FormClosed += new FormClosedEventHandler(MyForm_FormClosed); //Attached the event handler before firing ShowDialog
ShowProgress.ShowDialog();
}
}
ShowDialog synchronously shows a modal dialog, meaning it blocks until the form is closed (the following code is not run until the form is closed). Therefore, when ShowDialog returns the form is already closed.
You can attach the event handler before calling ShowDialog() as #Jade suggests, which will work, but honestly you do not need to use the event system at all. Simply wait for ShowDialog to return then perform the actions you would when the form is closed:
public void Update_Click(object sender, EventArgs e)
{
using (PccBiometricsHandler.Form1 ShowProgress = new PccBiometricsHandler.Form1())
{
menu.Items[2].Enabled = false;
ShowProgress.ShowDialog();
}
updaterAccess();
menu.Items[2].Enabled = true;
}
If you want to do this in VB:
AddHandler ShowProgress.FormClosed, AddressOf MyForm_FormClosed
I am trying to Direct the output of any Process given the PID to a Textbox on my Form such as cmd.exe
I use the following code but nothing is happening:
public partial class FormMain : Form
{
private Int32 PID = 0;
private Process process;
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
PID = Convert.ToInt32(textBox2.Text);
process = Process.GetProcessById(PID);
process.OutputDataReceived += process_OutputDataReceived;
}
void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
textBox1.Text += e.Data;
}
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
process.OutputDataReceived -= process_OutputDataReceived;
}
}
What am I doing wrong?
I think the problem with what you are trying to do is with the way you are using the event. The event only fires during async output operations.
You must set:
process.StartInfo.RedirectStandardOutput = true;
Then use async read operations which will fire the event:
process.BeginOutputReadLine();
You should read the documentation for that event:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx
Hi In my c# application I am trying to minimize application to systems tray, when the form is closed. Here is the code I have tried.
public void MinimizeToTray()
{
try
{
notifyIcon1.BalloonTipTitle = "Sample text";
notifyIcon1.BalloonTipText = "Form is minimized";
if (FormWindowState.Minimized == this.WindowState)
{
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(500);
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
notifyIcon1.Visible = false;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and I am calling the method to form closing event. But the problem is its not minimizing to tray. Its just closing the form.
e.Cancel = true; code will be always cancelling the event even if you shut the computer down, but here is a code that helps you:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
myNotifyIcon.Visible = true;
this.Hide();
e.Cancel = true;
}
}
It will allow closing the form programmaticaly.
Write a event in Form Closing event.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
Hide();
}
And write using Custom menu strip for notification icon for to show.
namespace MinimizeTrayNotification
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void MinimzedTray()
{
notifyIcon1.Visible = true;
notifyIcon1.Icon = SystemIcons.Application;
notifyIcon1.BalloonTipText = "Minimized";
notifyIcon1.BalloonTipTitle = "Your Application is Running in BackGround";
notifyIcon1.ShowBalloonTip(500);
}
private void MaxmizedFromTray()
{
notifyIcon1.Visible = true;
notifyIcon1.BalloonTipText = "Maximized";
notifyIcon1.BalloonTipTitle = "Application is Running in Foreground";
notifyIcon1.ShowBalloonTip(500);
}
private void Form1_Resize(object sender, EventArgs e)
{
if(FormWindowState.Minimized==this.WindowState)
{
MinimzedTray();
}
else if (FormWindowState.Normal == this.WindowState)
{
MaxmizedFromTray();
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.WindowState = FormWindowState.Normal;
Form1 frm = new Form1();
frm.Show();
MaxmizedFromTray();
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
this.WindowState = FormWindowState.Normal;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
this.Hide();
}
}
private void notifyIcon1_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
notifyIcon1.BalloonTipText = "Normal";
notifyIcon1.ShowBalloonTip(500);
}
}
}
You should cancel the FormClosing event and then call your MinimizeToTray() function.
This is done through the Cancel property of the FormClosingEventArgs.
Also, consider using a bool somewhere to allow closing the Form in some conditions, such as if you're using a File > Exit menu or something:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(!allowClosing)
{
e.Cancel = true;
MinimizeToTray();
}
}
To minimize when closing set WindowState to Minimized
private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
e.Cancel = true;
WindowState = FormWindowState.Minimized;
}
You need to use the FormClosing-Event.
private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
e.Cancel = true;
MinimizeToTray();
}
You can handle FormClosing Event such as micsoft Form Closing Event as Following example of C#
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Determine if text has changed in the textbox by comparing to original text.
if (textBox1.Text != strMyOriginalText)
{
// Display a MsgBox asking the user to save changes or abort.
if (MessageBox.Show("Do you want to save changes to your text?", "My Application",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// Cancel the Closing event from closing the form.
e.Cancel = true;
// Call method to save file...
}
}
}