Click here to Skip to main content
15,889,527 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Is there any equivalent for OnHandleCreated & WndProc functions for a Window Service similar to the one in C# for a form?

I need to implement WatchBP SDK(USB Library) for window Service that works with WebSocket to get data from the device to Web UI.

in SDK below methods need to implement but these methods not getting called in Window Service so notification not received from Device to window service.

protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);
        this.watchBPOfficeHid.RegisterHandle(this.Handle);
        
    }
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        this.watchBPOfficeHid.ParseMessages(ref m);
    }


although I inherit Window service class from System.Windows.Forms.Form but above method not getting called.

In WinForms we could use OnHandleCreated to get the handle as soon as it is created. Is it any alternative for this in window service?

Any help would be appreciated.
Thanks in advance.

What I have tried:

Is there any equivalent for OnHandleCreated & WndProc functions for a Window Service similar to the one in C# for a form?
Posted
Updated 4-Aug-20 5:35am

No. Services do not - and cannot - have a UI at all, cannot interact with the user, and do not respond to messages other than System messages. They do not have a Window Handle because ... they don't have a Window.

They can't be derived successfully from Form at all as a result.

You can't "work around" that - services are designed specifically to not have any UI components at all!
 
Share this answer
 
While you could in theory write a C# service that uses P/Invoke to do this (manage a hidden window), I doubt the effort required would weigh up against the one-use value of that approach.

I think you are far better off sticking to a Winforms (or WPF) application, and daemonising it (making it robust, restartable, able to minimise/hide) as much as you can and/or having a 'watchdog' process for it - in fact, if you start it through the Windows Task Scheduler, you may be able to specify the parameters to 'keep it alive', else write a watchdog service to monitor/restart your app
 
Share this answer
 
In order to give your service a UI you must add it to an account with a Allow Interaction With Desktop option set.

c# - Allow Windows service to interact with desktop - Stack Overflow[^]

Rather than duplicate the instructions, i provided this link for you. Hope it helps!

Anyway, you *should* be able to use Winforms from your service.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900