How to change a labels text based on a successful ping? - c#

So i have this program that needs to be connected to a certain server in our network, but in this case I will use 8.8.8.8. To make it easy to see if the connection is up I have a label that should say "yes" if connected and "no" if not. However I can't get it to work, this is the code I am using:
Sorry that wasn't descriptive enough indeed. It doesn't appear to do anything... Like the label doens't change at all. I've tried it on 2 different machine on Visual Studio 2017 and 2015. I can't wrap my head around it.
private void Form2_Load(object sender, EventArgs e)
{
timer1.Interval = 4000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
Ping ping = new Ping();
PingReply pingStatus = ping.Send(IPAddress.Parse("8.8.8.8"));
if (pingStatus.Status == IPStatus.Success)
{
label6.Text = "yes";
label6.ForeColor = Color.Blue;
}
else
{
label6.Text = "no";
label6.ForeColor = Color.Red;
}
}
Edit: changed != to ==

You will want to try something like the following;
private void Form2_Load(object sender, EventArgs e)
{
timer1.Interval = 4000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
string Address = "8.8.8.8";
PingHost(Address);
}
public bool PingHost(string Address)
{
bool Canping = false;
Ping ping = new Ping();
try
{
PingReply reply = ping.Send(Address);
label6.Text = reply.Status.ToString();
label6.ForeColor = Color.Blue;
}
catch (PingException e)
{
label6.Text = e.ToString();
label6.ForeColor = Color.Red;
}
return Canping;
}
This way by using NetworkInformation you can handle the returns a bit better.
However, having this check every 4 seconds might not be the best approach as this might have a knock on effect on performance but I guess this would all depend on what the application is needed for and the network you are pinging.
EDIT
The OP code does work but this maybe a more efficient way to handle this.

Related

Problem reading FT300 sensor data from Modbus EasyModbus.dll library in Windows form C#

I'm right now trying to read sensor data through USB-RS485 converter and utilizing the EasyModbus.dll in C#.
However, I've kept receiving CRC checked failed at the ReadHoldingRegister part. The connection and reading part is shown below.
I've already done lots of research but still can't solve the issue. Can anyone help me with this?
The CRC checked failed will occur at
int[] Read = modbusClient.ReadHoldingRegisters(179, 6);
The FT300 Modbus Setting is also shown below:
Image is stolen from this manual, page 34
void getavailableports() // get available COM
{
comboBox1.Items.Clear();
string[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void comboBox1_MouseClick(object sender, MouseEventArgs e) //let user choose COM
{
getavailableports();
}
private void Start_Click(object sender, EventArgs e) // Start button being pressed
{
try
{
Invoke(new EventHandler(ChangeColor));
//FT300Port.PortName = comboBox1.Text;
//.BaudRate = Convert.ToInt32(BaudRate.Text);
//FT300Port.Open();
modbusClient.UnitIdentifier = 9; // default slaveID = 1
modbusClient.Baudrate = Convert.ToInt32(BaudRate.Text); // default baudrate = 9600
modbusClient.Parity = System.IO.Ports.Parity.None;
modbusClient.StopBits = System.IO.Ports.StopBits.One;
modbusClient.ConnectionTimeout = 500;
modbusClient.Connect();
lb_status.Text = "Connected";
timer_Modbus.Enabled = true;
}
catch(Exception ex)
{
lb_status.Text = ex.ToString();
throw;
}
}
private void ChangeColor(object sender, EventArgs e)
{
Start.Text = "Streaming";
Start.BackColor = Color.Red;
}
private void Disconnect_Click(object sender, EventArgs e)
{
modbusClient.Disconnect();
Start.Text = "Start";
Start.BackColor = Color.DarkGray;
lb_status.Text = "Disconnected";
timer_Modbus.Enabled = false;
}
private void timer_Modbus_Tick(object sender, EventArgs e)
{
timer_Modbus.Enabled = false;
//modbusClient.WriteMultipleCoils(179, new bool[] { true, true, true, true, true, true});
//Write Coils starting with Address 180
//bool[] readCoils = modbusClient.ReadCoils(179, 6);
**int[] Read = modbusClient.ReadHoldingRegisters(179, 6);**
/*textBox1.Text = Convert.ToString(Read[0]);
textBox2.Text = Convert.ToString(Read[1]);
textBox3.Text = Convert.ToString(Read[2]);
textBox4.Text = Convert.ToString(Read[3]);
textBox5.Text = Convert.ToString(Read[4]);
textBox6.Text = Convert.ToString(Read[5]);*/
timer_Modbus.Enabled = true;
}

Loop Script not updating other forms

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";
}
}
}

Displaying different label text each second

I have three forms, From 1 is a main form and Form2 is splash screen and Form3 is a mini form.
So what i am trying to do is when ever i send a mail this From3 will pop up which has a gif image
and a label. So i am successfully able to make the From3 for 5 sec, in which the label will
change for different words for each second.
In form 3
i am using timer1 to run the mini form only for 5 seconds. and timer two to run only for 1 sec.
I guess we can do this in a better way which is pretty simple and easy.. Any good ideas and
help are most welcome!!!
Note:- Also when i again press the button send mail.. the label is starting from - Done!!.. Any helps.. The first time it starts from Connecting to smtp server..but on second time onwards its staring from Done!! then label going to Connecting to smtp server.. and so on!!
Here is my code:
Form1
private void sendmail_Click(object sender, EventArgs e)
{
//mail basic function here!!!!
smtp.Send(msg);
_f3.ShowDialog();//- - ->> goes to mini form Form3
smtp.Dispose();
MessageBox.Show("Email Successfully Sent!!!", "Mail!!!.");
}
Form3
private void Form3_Load(object sender, EventArgs e)
{
timer1.Interval = 5000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer2.Interval = 1000;
timer2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
timer1.Stop();
}
int StopTime = 0;
private void timer2_Tick(object sender, EventArgs e)
{
StopTime++;
if (StopTime == 1)
{
label1.Text = " Connecting to smtp server..";
}
if (StopTime == 2)
{
label1.Text = " Fetching recipients..";
}
if (StopTime == 3)
{
label1.Text = " Attaching G-code files..";
}
if (StopTime == 4)
{
label1.Text = " Done!!";
StopTime = 0;
timer2.Stop();
}
}
Does Form3 close after it displays Done? You could do something like this:
private void Form3_Load(object sender, EventArgs e)
{
SetLabel1Text(); //reset label text
timer1.Interval = 5000;
timer1.Enabled = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer2.Interval = 1000;
timer2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
timer1.Stop();
}
int StopTime = 0;
private void timer2_Tick(object sender, EventArgs e)
{
StopTime++;
SetLabel1Text();
if (StopTime == 4)
{
StopTime = 0;
timer2.Stop();
}
}
private void SetLabel1Text()
{
string[] label1Text = { " Connecting to smtp server..", " Connecting to smtp server..", " Fetching recipients..", " Attaching G-code files..", " Done!!" };
label1.Text = label1Text[StopTime]; //populate label from array of values
}

Check internet connection is available or not

I am trying to detect the internet connection, if the internet connection is available and it is connected, it will continue, otherwise it will throw message box says that the connection is not available.
What I am encounter is whether the internet connection is connected or not connected, the code will continue.
Here is the code:
** The program will continue to worker_ProgressChanged, even though there is no internet connection available **
public CheckUpdates()
{
InitializeComponent();
bool checkConnection = CheckConnection.IsConnectedToInternet();
progressBar1.Style = ProgressBarStyle.Marquee;
if (checkConnection == true)
{
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += new DoWorkEventHandler(worker_DoWork);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
}
else
{
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("No connection available, please check your internet connection!", "No connection");
if (_dialogResult == DialogResult.OK)
{
this.Hide();
this.Close();
}
}
}
private void CheckUpdates_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if (e.ProgressPercentage.Equals(100))
{
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Notify.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("No updates were available!", "No updates");
if (_dialogResult == DialogResult.OK)
{
this.Hide();
this.Close();
}
}
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_timer.Enabled = true;
_timer.Tick += new EventHandler(Timer_Tick);
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i++)
{
backgroundWorker1.ReportProgress(i);
System.Threading.Thread.Sleep(100);
}
}
void Timer_Tick(object sender, EventArgs e)
{
_timer.Enabled = false;
}
class CheckConnection
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
public static bool IsConnectedToInternet()
{
int Desc;
return InternetGetConnectedState(out Desc, 0);
}
}
Your answer much appreciated!
Thank you very much!
Because you call backgroundWorker1.RunWorkerAsync(); in the event WelcomeScreen_Load or in the event CheckUpdates_Load without checking if the Internet is connected or not. (Probably the worker_ProgressChanged is defined at design time withing the backgroundWorkder properties)
These events doesn't seems to be related to a Form.Load event handler because your class doesn't derive from Form. However it seems clear that you need to put a check there otherwise whoever triggers these events will start your background worker.
private void CheckUpdates_Load(object sender, EventArgs e)
{
if(CheckConnection.IsConnectedToInternet())
backgroundWorker1.RunWorkerAsync();
}
private void WelcomeScreen_Load(object sender, EventArgs e)
{
if(CheckConnection.IsConnectedToInternet())
backgroundWorker1.RunWorkerAsync();
}

C# UserControl Not and Yes with Text

The Default is No Checkbox
When I run the program and Click the Yes Checkbox the program overflowed
private void checkEdit1_Click(object sender, EventArgs e)
{
checkEdit2.Checked = false;
textEdit1.Enabled = true;
answered = true;
optional = textEdit1.Text;
if (!checkEdit1.Checked)
{
checkEdit1.Checked = true;
checkEdit2.Checked = false;
textEdit1.Enabled = true;
optional = textEdit1.Text;
}
}
private void checkEdit2_Click(object sender, EventArgs e)
{
checkEdit1.Checked = false;
textEdit1.Enabled = false;
answered = false;
if (!checkEdit2.Checked)
{
checkEdit2.Checked = true;
checkEdit1.Checked = false;
textEdit1.Enabled = false;
answered = false;
}
}
What you think is the error ?
Instead of the Click event you should use the CheckedChanged event in this way:
checkEdit1.CheckedChenged += new EventHandler(checkEdit1_CheckedChanged);
checkEdit2.CheckedChenged += new EventHandler(checkEdit2_CheckedChanged);
private void checkEdit1_CheckedChanged(object sender, EventArgs e)
{
if(checkEdit1.Checked == checkEdit2.Checked)
checkEdit2.Checked = !checkEdit.Checked;
}
private void checkEdit2_CheckedChanged(object sender, EventArgs e)
{
if(checkEdit1.Checked == checkEdit2.Checked)
checkEdit2.Checked = !checkEdit.Checked;
}
But the best way in this case is to use a group of radio buttons.
Assuming that those methods are wired up to checkEdit1 and checkEdit2 I would advise that you don't make a change to checkEdit1 in checkEdit1_Click as it has already changed - only modify the state of the alternate.
However, when you modify the state of the other, unless you're careful, you're going to get called back. Eventually the computer gives up -- the overflow!
As mentioned in a comment by #Cyborgx37, radio buttons are the better UX choice here!
A possible solution, bind a single method to the OnClick to BOTH checkboxes:
private bool internallyUpdating = false;
private void CheckboxClick(object sender, EventArgs e)
{
if ( !internallyUpdating )
{
// Prevent subsequent changes
internallyUpdating = true;
// Exchange 'checked' state
if ( sender == checkEdit1 )
{
checkEdit2.Checked = !checkEdit2.Checked;
}
else // if (sender == checkEdit2)
{
checkEdit1.Checked = !checkEdit1.Checked;
}
// other logic here..
// restore 'on change' functionality.
internallyUpdating = false;
}

Categories

Resources