Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a console application behave like a Windows application

Tags:

c#

.net

I have a console application, and I want it to wait till some event is raised. But it executes the code and exits:

static void Main(string[] args)
{
    var someObjectInstance = new SomeObject();
    someObjectInstance.SomeEvent += SomeEventHandler;
}

static void SomeEventHandler()
{
    //Some logic
}

I want to make my application behave like a Windows application where

Application.Run(new Form1());

is called and the message loop is run.

But I don't need neither a message loop nor any form. So it looks like overhead. Is there a more light-weight way to achieve my goal?

like image 476
SiberianGuy Avatar asked Aug 02 '10 17:08

SiberianGuy


People also ask

How Windows applications are different from console applications?

The sole difference is that a console application always spawns a console if it isn't started from one (or the console is actively suppressed on startup). A windows application, on the other hand, does not spawn a console. It can still attach to an existant console or create a new one using AllocConsole .

How can I open console application without Windows?

If you do not know what I am talking about: press Win+R, type “help” and press ENTER. A black console window will open, execute the HELP command and close again. Often, this is not desired. Instead, the command should execute without any visible window.


1 Answers

Add

Console.ReadLine(); after you attach your eventhandler.

For example..

class Program
{
    static void Main(string[] args)
    {
        System.IO.FileSystemWatcher watcher = new System.IO.FileSystemWatcher(@"c:\", "*.txt");
        watcher.Created += new System.IO.FileSystemEventHandler(watcher_Created);
        watcher.EnableRaisingEvents = true;
        Console.ReadLine();
    }

    static void watcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        Console.WriteLine(string.Format("{0} was created at {1:hh:mm:ss}", e.FullPath, DateTime.Now));
    }
}
like image 75
Greg Bogumil Avatar answered Oct 26 '22 21:10

Greg Bogumil