views:

79

answers:

1

I have a console app that I want to run continually in the background. I thought that if I started it up and then told it to wait things would work. But when I have it wait, it freezes the application.

Here is my code:

class Program { static public ManualResetEvent StopMain;

    static void Main(string[] args)
    {
        // Hide the cursor.
        Cursor.Current = Cursors.Default;

        StopMain = new ManualResetEvent(false);

        RunHook runHook = new RunHook();

        // wait until signalled by Program.StopMain.Set();
        StopMain.WaitOne();             

    }
}

class RunHook
{
    private HookKeys hook;
    public RunHook()
    {
        hook = new HookKeys();
        hook.HookEvent += EventForHook;
    }

    private void EventForHook(HookEventArgs e, KeyBoardInfo keyBoardInfo, 
      ref Boolean handled)
    {
        if ((keyBoardInfo.scanCode == 4) && (keyBoardInfo.vkCode == 114))
            handled = true;
    }
}

Any ideas on how to have this run in the background but never terminate?

+2  A: 

The behavior you see is expected. You have one thread, and it's in a wait state. To get some form of activity, you have to let the scheduler actually do something. A background thread is one way to achieve this:

static void Main(string[] args)    
{
    StopMain = new ManualResetEvent(false);
    bool exit = false;

    new Thread(
        delegate 
        { 
            new RunHook(); 
            while(!exit) { Thread.Sleep(1); }                 
        }
    ).Start();

    StopMain.WaitOne();
    exit = true;
}

Another is to just let the primary thread yield:

static void Main(string[] args)    
{
    StopMain = new ManualResetEvent(false);

    RunHook runHook = new RunHook(); 

    while(!StopMain.WaitOne())
    {
        Thread.Sleep(1);
    }
}

There are certainly other ways, too. Personally I'd do neither of these. Instead I'd add a blocking method to the RunHook class and have it return when it was done or signalled.

ctacke
thanks for your answer. Normally I would agree about doing none of these. But I am trying to disable the phone buttons on our devices, so I never want this to return (never, ever).I will give these a try and see how they do.
Vaccano
Alas, I tried both of these methods and they did not work. When the RunHook class had an event called it froze the system.
Vaccano