I am attempting to make an image control be displayed after a port check is run.
namespace MonitorFlux
{
public partial class Form1 : Form
{
PortChecks PortCheckObject = new PortChecks();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public static void CheckHTTP()
{
string hostname = "google.com";
int portno = 80;
IPAddress ipa = (IPAddress)Dns.GetHostAddresses(hostname)[0];
Form1 formobject = new Form1(); // Create new class object, so can call other methods in the class
try
{
System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
sock.Connect(ipa, portno);
if (sock.Connected == true) // Port is in use and connection is successful
{
MessageBox.Show("Port is Open");
formobject.displayGreen();
}
sock.Close();
}
catch (System.Net.Sockets.SocketException ex)
{
if (ex.ErrorCode == 10061) // Port is unused and could not establish connection
{
formobject.displayRed();
MessageBox.Show("Port is Closed");
}
else
{
MessageBox.Show(ex.Message);
}
}
}
public void displayGreen()
{
pictureBox2.Visible = false;
pictureBox1.Visible = true;
}
private void displayRed()
{
pictureBox2.Visible = true;
pictureBox1.Visible = false;
}
private void testCheck_Click(object sender, EventArgs e)
{
CheckHTTP();
// MessageBox.Show(PortCheckObject.httpport);
}
}
}
It won’t let me call a method from within the try clause e.g. displayRed()
So I create an object of Form1 class to run the displayRed() method, although when the method runs it doesn’t hide the image controls as expected. I assume this is because I have create another instance of the class. (If I run the method normally – not using an object, the image controls are hidden correctly.)
So I guess my questions is how can I get around this issue?
Please let me know if I have not explained the situation very well and I’ll try my best to elaborate. Thanks
CheckHTTPisstaticand you can’t call instance methods from a static method unless, like you’ve shown, you create a new object in that method, in which case you are working with a different object so you likely won’t get the behavior you want.