Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7191551
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T19:45:13+00:00 2026-05-28T19:45:13+00:00

I have a method that loops ping requests, and I’d like when I click

  • 0

I have a method that loops ping requests, and I’d like when I click Ctrl+c, it break the loop and give me statics like the normal cmd, but when I click Ctrl+c, I get

Press Any Key To Continue… <<

and then program closes .

For example : ping google.com -t << that will ping google with endless loop, but I need to break the loop ONLY when I click Ctrl+c

private void _t(string website)
{
    Ping pingSender = new Ping();
    string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    byte[] buffer = Encoding.ASCII.GetBytes(data);
    int timeout = 10000;
    try
    {
        PingOptions options = new PingOptions(64, false);
        PingReply send0 = pingSender.Send(website, timeout, buffer, options);
        Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
        while (1 < 2)
        {
            PingReply reply = pingSender.Send(website, timeout, buffer, options);

            if (reply.Status == IPStatus.Success)
            {
                Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime / 5, reply.Options.Ttl);
            }
            else
            {
                Console.WriteLine("Request timed out.");
            }
        }
    }
    catch
    {
        Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
    }
}

But instead of using while (1<2), I want to use something like :

while (ConsoleKeyInfo.Equals("Control + c") not clicked) // sure it is wrong , but that`s what I wanna achieve
{
    PingReply reply = pingSender.Send(website, timeout, buffer, options);

    if (reply.Status == IPStatus.Success)
    {
        Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}",        reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime / 5, reply.Options.Ttl);
    }
    else
    {
        Console.WriteLine("Request timed out.");
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T19:45:14+00:00Added an answer on May 28, 2026 at 7:45 pm

    There is a fairly complete tutorial (with code) here. I did a quick test and their example actually worked (imagine that).

    Here is their code:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Xml;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Runtime.InteropServices;
    using System.Threading;
    using System.Reflection;
    
    namespace ConsoleApplication1
    {
    
        class ControlChecker
        {
            #region GLOBAL VARS
            private static readonly Mutex mutex = new Mutex(true, Assembly.GetExecutingAssembly().GetName().CodeBase);
            private static bool _userRequestExit = false;
            private static bool _doIStop = false;
            static HandlerRoutine consoleHandler;
            #endregion
    
            [DllImport("Kernel32")]
            public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
    
            // A delegate type to be used as the handler routine for SetConsoleCtrlHandler.
            public delegate bool HandlerRoutine(CtrlTypes CtrlType);
    
            // An enumerated type for the control messages sent to the handler routine.
            public enum CtrlTypes
            {
                CTRL_C_EVENT = 0,
                CTRL_BREAK_EVENT,
                CTRL_CLOSE_EVENT,
                CTRL_LOGOFF_EVENT = 5,
                CTRL_SHUTDOWN_EVENT
            }
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="ctrlType"></param>
            /// <returns></returns>
            private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
            {
                // Put your own handler here
                switch (ctrlType)
                {
                    case CtrlTypes.CTRL_C_EVENT:
                        _userRequestExit = true;
                        Console.WriteLine("CTRL+C received, shutting down");
                        break;
    
                    case CtrlTypes.CTRL_BREAK_EVENT:
                        _userRequestExit = true;
                        Console.WriteLine("CTRL+BREAK received, shutting down");
                        break;
    
                    case CtrlTypes.CTRL_CLOSE_EVENT:
                        _userRequestExit = true;
                        Console.WriteLine("Program being closed, shutting down");
                        break;
    
                    case CtrlTypes.CTRL_LOGOFF_EVENT:
                    case CtrlTypes.CTRL_SHUTDOWN_EVENT:
                        _userRequestExit = true;
                        Console.WriteLine("User is logging off!, shutting down");
                        break;
                }
    
                return true;
            }
    
            /// <summary>
            /// Main entry point
            /// </summary>
            /// <param name="args"></param>
            /// <returns></returns>        
            static int Main(string[] args)
            {
                try
                {
                    //make sure we only have one....
                    if (!mutex.WaitOne(TimeSpan.Zero, true))
                    {
                        Console.WriteLine("Another instance already running");
                        Thread.Sleep(5000);
                        return 1;
                    }
    
                    //save a reference so it does not get GC'd
                    consoleHandler = new HandlerRoutine(ConsoleCtrlCheck);
    
                    //set our handler here that will trap exit
                    SetConsoleCtrlHandler(consoleHandler, true);
    
                    DoMyTask();
    
                    return 0;
                }
                catch (Exception x)
                {
                    Console.WriteLine("Main Error [{0}]", x.Message);
                    return -1;
                }
            }
    
    
    
            /// <summary>
            /// Run the export
            /// </summary>
            /// <param name="pAuthority"></param>
            /// <returns></returns>
            private static void DoMyTask()
            {
                //execcute until we have no more records to process
                while (!_doIStop)
                {
                    //did user request exit?
                    if (_userRequestExit)
                    {
                        _doIStop = true;    //set flag to exit loop.  Other conditions could cause this too, which is why we use a seperate variable
                        Console.WriteLine("Shutting down, user requested exit");
                        break;
                    }
    
                    //do some other stuff here
                    Console.WriteLine(String.Format("{0}, no exit requested yet...", DateTime.Now));
                    //sleep 1 second
                    Thread.Sleep(1000);    
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a method that looks like this: public static String escape(String text) {
I have a method that looks like: T[] field; public Method(IList<T> argument) { this.field
I have a C++ method signature that looks like this: static extern void ImageProcessing(
I have a method on an interface that looks like this and I want
I have a method in a url rewriting module that looks like this public
I have a method right now that loops through a list of business objects
I have a method that loops through a list and creates Links using the
I have a while loop that loops until bool done = true; In the
I have a method that loops through a list of guids and saves them
I have a method that loops through all the rows of a table where

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.