. NET instance code for implementing interactive WINDOWS Services

Source: Internet
Author: User

I want to be a file monitoring service over the past few days. I have read many articles about WINDOWS services on the Internet. I only talked about how to make the most basic service, but it does not show how to interact with users. Check MSDN and see the description about the service:

Windows service applications run in a window area different from the login user's interaction area. The window area is a security object that contains the clipboard, a group of global atoms, and a group of desktop objects. Because the Windows Service region is not an Interactive region, the dialog box raised in the Windows service application is invisible and may cause the program to stop responding. Similarly, the error information should be recorded in the Windows event log, rather than in the user interface.

The Windows service class supported by. NET Framework does not support interaction with the interactive area (that is, the login user. At the same time,. NET Framework does not contain classes that represent regions and desktops. If the Windows Service must interact with other regions, you need to access the unmanaged Windows API.

That is to say, to implement interactive services (for example, if we want to set some parameters for the service at Runtime), we must use System. Runtime. InteropServices.

Let's take a look at how to implement an interactive service. The steps are the same as implementing basic services (you can refer to MSDN or google ).

When implementing OnStart, note that a FORM or something cannot be displayed here. There is no response to this. We can run a thread in this method. This thread needs to access window area objects or desktop objects. Of course, these are not provided in the framework, and they need to access unmanaged code.

Let's take a look at the code and try again.

Copy codeThe Code is as follows: using System;
Using System. Collections;
Using System. ComponentModel;
Using System. Data;
Using System. Diagnostics;
Using System. ServiceProcess;
Using System. Threading;
Using System. Runtime. InteropServices;
Namespace FileWatchService
{
Publicclass Service1: System. ServiceProcess. ServiceBase
{
///
/// Required designer variables.
///
Private System. ComponentModel. Container components = null;
Thread threadForm = null;
Public Service1 ()
{
// This call is required by the Windows. Forms component designer.
InitializeComponent ();

// TODO: add any initialization after the InitComponent call
}

# Code generated by the region component designer
///
/// The designer supports the required methods-do not use the code editor
/// Modify the content of this method.
///
Privatevoid InitializeComponent ()
{
//
// Service1
//
This. ServiceName = "JadeWatchService ";

}
# Endregion
[STAThread]
Staticvoid Main ()
{
System. ServiceProcess. ServiceBase. Run (new Service1 ());

}
///
/// Clear all resources in use.
///
Protectedoverrisponid Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

///
/// Set specific operations so that the service can perform its work.
///
Protectedoverridevoid OnStart (string [] args)
{
ThreadForm = new Thread (new ThreadStart (FormShow ));
ThreadForm. Start ();
}

///
/// Stop the service.
///
Protectedoverrisponid OnStop ()
{
If (threadForm! = Null)
{
If (threadForm. IsAlive)
{
ThreadForm. Abort ();
ThreadForm = null;
}
}
}

Void FormShow ()
{

Getasktopwindow ();
IntPtr hwinstaSave = GetProcessWindowStation ();
IntPtr dwThreadId = GetCurrentThreadId ();
IntPtr hsf-save = GetThreadDesktop (dwThreadId );
IntPtr hwinstaUser = OpenWindowStation ("WinSta0", false, 33554432 );
If (hwinstaUser = IntPtr. Zero)
{
RpcRevertToSelf ();
Return;
}
SetProcessWindowStation (hwinstaUser );
IntPtr hsf-user = OpenDesktop ("Default", 0, false, 33554432 );
RpcRevertToSelf ();
If (hsf-user = IntPtr. Zero)
{
SetProcessWindowStation (hwinstaSave );
CloseWindowStation (hwinstaUser );
Return;
}
SetThreadDesktop (hsf-user );

IntPtr dwGuiThreadId = dwThreadId;

Form1 f = new Form1 (); // This FORM1 can contain policyicon, which can be displayed in the tray. You can click the tray icon to set it.
System. Windows. Forms. Application. Run (f );

DwGuiThreadId = IntPtr. Zero;
SetThreadDesktop (hsf-save );
SetProcessWindowStation (hwinstaSave );
CloseDesktop (hsf-user );
CloseWindowStation (hwinstaUser );
}

[DllImport ("user32.dll")]
Staticexternint getasktopwindow ();

[DllImport ("user32.dll")]
Staticextern IntPtr GetProcessWindowStation ();

[DllImport ("kernel32.dll")]
Staticextern IntPtr GetCurrentThreadId ();

[DllImport ("user32.dll")]
Staticextern IntPtr GetThreadDesktop (IntPtr dwThread );

[DllImport ("user32.dll")]
Staticextern IntPtr OpenWindowStation (string a, bool B, int c );

[DllImport ("user32.dll")]
Staticextern IntPtr OpenDesktop (string lpszDesktop, uint dwFlags,
Bool fInherit, uint dwDesiredAccess );

[DllImport ("user32.dll")]
Staticextern IntPtr CloseDesktop (IntPtr p );

[DllImport ("rpcrt4.dll", SetLastError = true)]
Staticextern IntPtr RpcImpersonateClient (int I );

[DllImport ("rpcrt4.dll", SetLastError = true)]
Staticextern IntPtr RpcRevertToSelf ();

[DllImport ("user32.dll")]
Staticextern IntPtr SetThreadDesktop (IntPtr );

[DllImport ("user32.dll")]
Staticextern IntPtr SetProcessWindowStation (IntPtr );
[DllImport ("user32.dll")]
Staticextern IntPtr CloseWindowStation (IntPtr );
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.