❔ 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
Shinigami2y ago
Need more context
krnlException
krnlExceptionOP2y 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
Shinigami2y ago
Can you paste code of what you've done ?
krnlException
krnlExceptionOP2y 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
Jimmacle2y ago
Console.CancelKeyPress
Shinigami
Shinigami2y ago
Yes @nolemretaW you can use Console.CancelKeyPress In main you can write Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
krnlException
krnlExceptionOP2y ago
Okay, thank you, it works
Jimmacle
Jimmacle2y ago
you don't need to explicitly instantiate a delegate like that just Console.CancelKeyPress += MyHandlerMethod
Shinigami
Shinigami2y ago
Ohh something new to learn, thanks.
Jimmacle
Jimmacle2y ago
i think you used to have to, so a lot of old documentation for winforms and stuff shows it that way
Accord
Accord2y 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.
Want results from more Discord servers?
Add your server