Can't keep cmd from opening when my GUI pings

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

40 Replies - 2243 Views - Last Post: 23 March 2020 - 08:04 AM Rate Topic: -----

#1 albert003   User is offline

  • D.I.C Addict

Reputation: 37
  • View blog
  • Posts: 819
  • Joined: 15-December 14

Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 11:10 AM

I've been working on making some GUI's and I am stuck on my current project. I still have more to add, but I want to get this part working before I make more progress on the program.

The plan for this program is to ping in this order
127.0.0.1
ping google.com
ping gateway IP (Had to use powershell. Couldn't figure it out otherwise)
ping IPV6

Right now when it pings 127.0.0.1 it displays the results in the textbox. But the cmd window opens and I've tried everything I could think of to fix it but I can't make the program run without having the cmd window open up as well.

This is the program.


private void btnbutton1_Click(object sender, EventArgs e)
        {
            Process test = new Process();
            test.StartInfo.FileName = "ipconfig";
            test.StartInfo.UseShellExecute = false;
            test.StartInfo.Arguments = "/all";
            test.StartInfo.RedirectStandardOutput = true;
            test.Start();
            textBox1.Text = test.StandardOutput.ReadToEnd();

        }

This post has been edited by albert003: 17 February 2020 - 11:10 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Can't keep cmd from opening when my GUI pings

#2 modi123_1   User is offline

  • Suitor #2
  • member icon



Reputation: 15567
  • View blog
  • Posts: 62,335
  • Joined: 12-June 08

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 11:12 AM

I remember there's an option in the startinfo about not creating a new window. Maybe check that out?

https://docs.microso...etframework-4.8
Was This Post Helpful? 1
  • +
  • -

#3 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7290
  • View blog
  • Posts: 24,673
  • Joined: 05-May 12

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 11:41 AM

I know your question is about how to suppress the console window, but you could just use the built in .NET Framework Ping class to do your pings.
Was This Post Helpful? 1
  • +
  • -

#4 Sheepings   User is offline

  • D.I.C Lover
  • member icon

Reputation: 237
  • View blog
  • Posts: 1,282
  • Joined: 05-December 13

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 04:26 PM

This is how you do it. A nice multi-threaded example for you. StartInfo.CreateNoWindow = true; provides the API call you need to not show a window and takes care of this for you.
        public delegate void DelegateCallback(string s);

        private void MainMethod(string[] of_addresses)
        {
            List<string> addresses = new List<string>();
            addresses.AddRange(of_addresses);
            Task.Run(() =>
            {
                addresses.ForEach(delegate (string current_address)
                {
                    Process cmd = new Process();
                    cmd.StartInfo.FileName = "cmd.exe";
                    cmd.StartInfo.UseShellExecute = false;
                    cmd.StartInfo.CreateNoWindow = true;
                    cmd.StartInfo.Arguments = $"/c ping {current_address}";
                    cmd.StartInfo.RedirectStandardOutput = true;
                    cmd.Start();
                    textBox1.Invoke(new DelegateCallback(UpdateUI), new string[] { cmd.StandardOutput.ReadToEnd() });
                });
            });
        }
        private void UpdateUI(string item)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Insert(0, textBox1.Text);
            stringBuilder.Append(item);
            textBox1.Text = stringBuilder.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string[] ips = { "127.0.0.1", "google.com" };
            MainMethod(ips);
        }



Screenshot : https://prnt.sc/r3s1jg

What else are you needing to get?

This post has been edited by Sheepings: 17 February 2020 - 04:31 PM

Was This Post Helpful? 2
  • +
  • -

#5 Sheepings   User is offline

  • D.I.C Lover
  • member icon

Reputation: 237
  • View blog
  • Posts: 1,282
  • Joined: 05-December 13

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 04:51 PM

Actually change from this :
    Task.Run(() =>
    {
        addresses.ForEach(delegate (string current_address)
        {
            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.UseShellExecute = false;
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.Arguments = $"/c ping {current_address}";
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.Start();
            textBox1.Invoke(new DelegateCallback(UpdateUI), new string[] { cmd.StandardOutput.ReadToEnd() });
        });
    });

To This :

            Task.Run(() =>
            {
                Process cmd = new Process();
                addresses.ForEach(delegate (string current_address)
                {
                    cmd.StartInfo.FileName = "cmd.exe";
                    cmd.StartInfo.UseShellExecute = false;
                    cmd.StartInfo.CreateNoWindow = true;
                    cmd.StartInfo.Arguments = $"/c ping {current_address}";
                    cmd.StartInfo.RedirectStandardOutput = true;
                    cmd.Start();
                    textBox1.Invoke(new DelegateCallback(UpdateUI), new string[] { cmd.StandardOutput.ReadToEnd() });
                });
            });

That way you are not creating a new process for each new ip you want to ping. You can utilise the same process but execute it with the new parameters of each iteration from the same process, which is more efficient.
Was This Post Helpful? 1
  • +
  • -

#6 Sheepings   User is offline

  • D.I.C Lover
  • member icon

Reputation: 237
  • View blog
  • Posts: 1,282
  • Joined: 05-December 13

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 08:06 PM

Here are a few more changes for you, and I've even adapted finding you your gateway address, which actually wasn't difficult, since all you needed to do was look around in the obvious place of the System.Net.NetworkInformation. Further poking around, I found it easier to loop through to eventually pull the hardware info. Anyway here are some of the changes. If you would prefer to pass your commands into the method. Such as ping, tracert etc. Simply change these lines :
private void MainMethod(string[] of_addresses)


To :
        private void MainMethod(string[] of_addresses, string command)



Change :
	            cmd.StartInfo.Arguments = $"/c ping {current_address}";


To :
              cmd.StartInfo.Arguments = string.Concat($"{command}", string.Empty.PadRight(1), $"{current_address}");

Change :
private void button1_Click(object sender, EventArgs e)
{
    string[] ips = { "127.0.0.1", "google.com" };
    MainMethod(ips);
}


To :
        private void button1_Click(object sender, EventArgs e)
        {
            string[] ips = { "127.0.0.1", "google.com" };
            string GatewayAddress = Return_Gateway();
            if (!string.IsNullOrEmpty(GatewayAddress))
                Console.WriteLine($"Your Gateway address is: {GatewayAddress}");
            MainMethod(ips, "/c ping");
        }

Lastly, add :
        public static string Return_Gateway()
        {
            foreach (NetworkInterface device in NetworkInterface.GetAllNetworkInterfaces())
            {
                GatewayIPAddressInformationCollection protocol_address = device.GetIPProperties().GatewayAddresses;
                if (protocol_address.Count > 0)
                {
                    foreach (GatewayIPAddressInformation address in protocol_address)
                    {
                        return string.Format("{0}", address.Address.ToString());
                    }
                }
            }
            return string.Empty;
        }

Now to get your IPV6 address, I suggest going through System.Net.Sockets.AddressFamily.InterNetworkV6 for that.

Hope all this helped.

This post has been edited by Sheepings: 17 February 2020 - 08:08 PM

Was This Post Helpful? 2
  • +
  • -

#7 albert003   User is offline

  • D.I.C Addict

Reputation: 37
  • View blog
  • Posts: 819
  • Joined: 15-December 14

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 08:35 PM

I'm so sorry I posted the wrong code. This is how I have it right now and when ti runs the cmd window appears. I will try your suggestions.

string command = "127.0.0.1 -4";
            
            Process test = new Process();
            test.StartInfo.FileName = "ping.exe";
            test.StartInfo.UseShellExecute = false;
            test.StartInfo.Arguments = command;
            test.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//
            test.StartInfo.RedirectStandardOutput = true;
            test.Start();
            textBox1.Text = test.StandardOutput.ReadToEnd();




You see originally, I tried to do this not using cmd ...


[code]for (int x = 0; x < 10; x++)
            {
                
                using(Ping p = new Ping())
                {
                    first = (textBox1.Text);
                    textBox1.Text = (first).ToString();
                    textBox1.Text = (p.Send("127.0.0.1").RoundtripTime.ToString() + "ms\n");
                }
            }
[/code]


But it would only show the time it pinged but not the details and I couldn't figure out how to make it ping more than once. I tried everything and I just couldn't do it. Which is why I returned to what I used when I initially wrote this program to work on command line with the GUI version.

This post has been edited by albert003: 17 February 2020 - 08:41 PM

Was This Post Helpful? 0
  • +
  • -

#8 Sheepings   User is offline

  • D.I.C Lover
  • member icon

Reputation: 237
  • View blog
  • Posts: 1,282
  • Joined: 05-December 13

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 08:39 PM

That return gateway function is rather lengthy and ugly for my taste, and it can also be written like this, which I prefer :
        public static string Return_Gateway()
        {
            for (int i = 0; i < NetworkInterface.GetAllNetworkInterfaces().Length; i++)
            {
                if (NetworkInterface.GetAllNetworkInterfaces()[i].GetIPProperties().GatewayAddresses.Count > 0)
                    using (IEnumerator<GatewayIPAddressInformation> enumerate = NetworkInterface.GetAllNetworkInterfaces()[i].GetIPProperties().GatewayAddresses.GetEnumerator())
                        while (enumerate.MoveNext())
                            return string.Format("{0}", enumerate.Current.Address.ToString());
            }
            return string.Empty;
        }

Which is a bit more tidy and still works almost exactly the same but more efficiently. No doubt Skydiver will probably want to plug it with some of his own improvements.
Was This Post Helpful? 1
  • +
  • -

#9 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7290
  • View blog
  • Posts: 24,673
  • Joined: 05-May 12

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 08:40 PM

Perhaps I am missing something, but since "ping" is not an CMD keyword/command, why even run CMD.EXE? "ping.exe" is a real executable. Why not change:
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = $"/c ping {current_address}";


to
cmd.StartInfo.FileName = "ping.exe";
cmd.StartInfo.Arguments = $"/c {current_address}";



What is starting CMD.EXE buying you?
Was This Post Helpful? 1
  • +
  • -

#10 Sheepings   User is offline

  • D.I.C Lover
  • member icon

Reputation: 237
  • View blog
  • Posts: 1,282
  • Joined: 05-December 13

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 08:51 PM

View PostSkydiver, on 18 February 2020 - 03:40 AM, said:

Perhaps I am missing something, but since "ping" is not an CMD keyword/command, why even run CMD.EXE?

Because that is what the OP wanted to do. You had already provided recommendation for the ping class. Given the way the OP wanted to do it, I could understand that he wanted to execute the ping command as though running it through cmd, and of course it was also obvious from his attempt that they wanted to capture the output of the window by using the cmd.StartInfo.RedirectStandardOutput = true; => which indicates whether the textual output of an application is written to the StandardOutput stream.

Secondly, maybe I am wrong but I think cmd offers more than just ping. With my presentation, the OP can also switch : cmd.StartInfo.Arguments = $"/c ping {current_address}"; for cmd.StartInfo.Arguments = $"/c tracert {current_address}"; - And if you take that into consideration with my recent updates. I think that my way is better and offers room for expansion if needed. Does Ping.exe offer anything more than just ping?



ping.exe" is a real executable. - Getting deja voo here... We've been here before on this subject. lol

This post has been edited by Sheepings: 17 February 2020 - 08:53 PM

Was This Post Helpful? 1
  • +
  • -

#11 albert003   User is offline

  • D.I.C Addict

Reputation: 37
  • View blog
  • Posts: 819
  • Joined: 15-December 14

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 08:55 PM

I used ping.exe because I honestly thought I had to use it when I wanted to use cmd. For example in one of my previous posts you were helping me I used cmd.exe. Now I know the proper way to use it now that you have shown me. Thank you for your help.
Was This Post Helpful? 0
  • +
  • -

#12 Sheepings   User is offline

  • D.I.C Lover
  • member icon

Reputation: 237
  • View blog
  • Posts: 1,282
  • Joined: 05-December 13

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 09:02 PM

albert003 - It's your call whichever way you want to do it. There is very little difference between these two options.

Regarding your issue for hiding the window. You would be better replacing :

test.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//


With :

test.StartInfo.CreateNoWindow = true;


If my intuition serves me correct, your parameter will insist on a window being created, but hidden. Whereas my method insists no such window be created.
Was This Post Helpful? 1
  • +
  • -

#13 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7290
  • View blog
  • Posts: 24,673
  • Joined: 05-May 12

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 09:06 PM

View PostSheepings, on 17 February 2020 - 10:39 PM, said:

That return gateway function is rather lengthy and ugly for my taste, and it can also be written like this, which I prefer :
        public static string Return_Gateway()
        {
            for (int i = 0; i < NetworkInterface.GetAllNetworkInterfaces().Length; i++)
            {
                if (NetworkInterface.GetAllNetworkInterfaces()[i].GetIPProperties().GatewayAddresses.Count > 0)
                    using (IEnumerator<GatewayIPAddressInformation> enumerate = NetworkInterface.GetAllNetworkInterfaces()[i].GetIPProperties().GatewayAddresses.GetEnumerator())
                        while (enumerate.MoveNext())
                            return string.Format("{0}", enumerate.Current.Address.ToString());
            }
            return string.Empty;
        }

Which is a bit more tidy and still works almost exactly the same but more efficiently. No doubt Skydiver will probably want to plug it with some of his own improvements.


Actually, not very efficient. Notice that NetworkInterface.GetAllNetworkInterfaces() is called 3 * NetworkInterface.GetAllNetworkInterfaces().Length times in the worse case of the gateway being found in the last interface.

Here are my variations on the above code:
public static string Return_Gateway2()
{
    var ifaces = NetworkInterface.GetAllNetworkInterfaces();
    for (int i = 0; i < ifaces.Length; i++)
    {
        if (ifaces[i].GetIPProperties().GatewayAddresses.Count > 0)
            using (IEnumerator<GatewayIPAddressInformation> enumerate = ifaces[i].GetIPProperties().GatewayAddresses.GetEnumerator())
                while (enumerate.MoveNext())
                    return string.Format("{0}", enumerate.Current.Address.ToString());
    }
    return string.Empty;
}

public static string Return_Gateway3()
{
    var ifaces = NetworkInterface.GetAllNetworkInterfaces();
    for (int i = 0; i < ifaces.Length; i++)
    {
        var addresses = ifaces[i].GetIPProperties().GatewayAddresses;
        if (addresses.Count > 0)
            using (IEnumerator<GatewayIPAddressInformation> enumerate = addresses.GetEnumerator())
                while (enumerate.MoveNext())
                    return string.Format("{0}", enumerate.Current.Address.ToString());
    }
    return string.Empty;
}

public static string Return_Gateway4()
{
    var ifaces = NetworkInterface.GetAllNetworkInterfaces();
    foreach(var iface in NetworkInterface.GetAllNetworkInterfaces())
    {
        foreach(var address in iface.GetIPProperties().GatewayAddresses)
            return address.Address.ToString();                
    }
    return string.Empty;
}

public static string Return_Gateway5()
{
    return NetworkInterface.GetAllNetworkInterfaces()
                            .SelectMany(iface => iface.GetIPProperties().GatewayAddresses)
                            .Select(address => address.Address.ToString())
                            .FirstOrDefault() ?? String.Empty;
}


Was This Post Helpful? 1
  • +
  • -

#14 Sheepings   User is offline

  • D.I.C Lover
  • member icon

Reputation: 237
  • View blog
  • Posts: 1,282
  • Joined: 05-December 13

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 09:13 PM

View Postalbert003, on 18 February 2020 - 03:55 AM, said:

I used ping.exe because I honestly thought I had to use it when I wanted to use cmd. For example in one of my previous posts you were helping me I used cmd.exe. Now I know the proper way to use it now that you have shown me. Thank you for your help.

Oh no. You don't have to use ping.exe. You can use cmd too as I have demonstrated, but be sure to not drop that c/ from your command or it will not work at all. I actually think cmd offers more room for expanding commands should this be something you want to do later on.

Either, mine or Skydivers methods will work. But I think ping might be more restrictive but may be more straightforward if pinging is all you want to do.

Hopefully you found some of that info I provided useful and you are welcome.

Have a good night!
Was This Post Helpful? 0
  • +
  • -

#15 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7290
  • View blog
  • Posts: 24,673
  • Joined: 05-May 12

Re: Can't keep cmd from opening when my GUI pings

Posted 17 February 2020 - 09:15 PM

View PostSheepings, on 17 February 2020 - 10:51 PM, said:

it was also obvious from his attempt that they wanted to capture the output of the window by using the cmd.StartInfo.RedirectStandardOutput = true; => which indicates whether the textual output of an application is written to the StandardOutput stream.

Redirecting standard output is not dependent on CMD.EXE. All Windows programs support it. It's in the CPM/DOS legacy of Windows.

View PostSheepings, on 17 February 2020 - 10:51 PM, said:

Secondly, maybe I am wrong but I think cmd offers more than just ping. With my presentation, the OP can also switch : cmd.StartInfo.Arguments = $"/c ping {current_address}"; for cmd.StartInfo.Arguments = $"/c tracert {current_address}";

No, it's not CMD that offers up ping.exe and tracert.exe. It's Windows itself that offer up these commands and all commands that are within the search PATH environment variable.

View PostSheepings, on 17 February 2020 - 10:51 PM, said:

And if you take that into consideration with my recent updates. I think that my way is better and offers room for expansion if needed. Does Ping.exe offer anything more than just ping?

What using CMD.EXE offers you is a chance to not have to think about whether the passed in command parameter is a built in DOS/CMD command or an executable that can be found in the PATH environment variable. Example, "DATE" and "TIME" or DOS/CMD commands. They are not executables.

View PostSheepings, on 17 February 2020 - 10:51 PM, said:

ping.exe" is a real executable. - Getting deja voo here... We've been here before on this subject. lol

Yes. Me too.
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3