C
C#15mo ago
nolemretaW

❔ Processing window messages in while loop in console

How do I process window messages while my code is in a while(true) loop with Thread.Sleep() in console? Because I need my code to run in a loop until user closes the window.
11 Replies
Shinigami
Shinigami15mo ago
Need more context
nolemretaW
nolemretaW15mo ago
My app has a while(running) loop and running bool controls that while loop, and I need my app to process window messages (such as user clicking X on window, or Ctrl+C to exit) in that loop So basically I need some way to set that running bool to false when user wants to close the window.
Shinigami
Shinigami15mo ago
Can you paste code of what you've done ?
nolemretaW
nolemretaW15mo ago
using System.Diagnostics;
using System.Runtime.InteropServices;

class Program
{
static void Main(string[] args)
{
bool running = true;
while (running)
{
//code
Thread.Sleep(1000);
}
}
}
using System.Diagnostics;
using System.Runtime.InteropServices;

class Program
{
static void Main(string[] args)
{
bool running = true;
while (running)
{
//code
Thread.Sleep(1000);
}
}
}
I know there's a Form.FormClosing event on WinForms, but is there a similar one for console apps
Jimmacle
Jimmacle15mo ago
Console.CancelKeyPress
Shinigami
Shinigami15mo ago
Yes @nolemretaW you can use Console.CancelKeyPress In main you can write Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
nolemretaW
nolemretaW15mo ago
Okay, thank you, it works
Jimmacle
Jimmacle15mo ago
you don't need to explicitly instantiate a delegate like that just Console.CancelKeyPress += MyHandlerMethod
Shinigami
Shinigami15mo ago
Ohh something new to learn, thanks.
Jimmacle
Jimmacle15mo ago
i think you used to have to, so a lot of old documentation for winforms and stuff shows it that way
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.