.NET实现可交互的WINDOWS服务的实例代码

所属分类: 网络编程 / ASP.NET 阅读数: 866
收藏 0 赞 0 分享

  这几天想做个文件监控服务,看了一下网上的关于WINDOWS服务的文章,数量都不少,都只讲了如何做一个最基本的服务,却没有讲述如何与用户进行交互。查看了MSDN,看一下关于服务的描述:

   Windows 服务应用程序在不同于登录用户的交互区域的窗口区域中运行。窗口区域是包含剪贴板、一组全局原子和一组桌面对象的安全对象。由于 Windows 服务的区域不是交互区域,因此 Windows 服务应用程序中引发的对话框将是不可见的,并且可能导致程序停止响应。同样,错误信息应记录在 Windows 事件日志中,而不是在用户界面中引发。

   .NET Framework 支持的 Windows 服务类不支持与交互区域(即登录用户)进行交互。同时,.NET Framework 不包含表示区域和桌面的类。如果 Windows 服务必须与其他区域进行交互,则需要访问非托管的 Windows API。

  也就是说我们要实现可交互的服务(比如我们想给服务在运行时做一些参数设置等),那我们一定要using System.Runtime.InteropServices

  那么来看一下如果才能实现一个可交互的服务呢。步骤与实现基本的服务一样(各位可自行参考MSDN或网上google一下).

  在实现OnStart时要注意,这里可不能弹出一个FORM什么的。这样做是没有任何反应的。我们可以在这个方法里运行一个线程。该线程需要访问窗口区域对象或桌面对象,当然 framework里是没有提供这些的,要访问非托管代码的。

  来看一下代码,再运行试一下。

复制代码 代码如下:

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
    {
        ///
        /// 必需的设计器变量。
        ///
private System.ComponentModel.Container components =null;
        Thread threadForm =null;
        public Service1()
        {
            // 该调用是 Windows.Forms 组件设计器所必需的。
            InitializeComponent();

            // TODO: 在 InitComponent 调用后添加任何初始化
        }

        #region 组件设计器生成的代码
        ///
        /// 设计器支持所需的方法 - 不要使用代码编辑器
        /// 修改此方法的内容。
        ///
privatevoid InitializeComponent()
        {
            //
            // Service1
            //
this.ServiceName ="JadeWatchService";

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

        }
        ///
        /// 清理所有正在使用的资源。
        ///
protectedoverridevoid Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components !=null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        ///
        /// 设置具体的操作,以便服务可以执行它的工作。
        ///
protectedoverridevoid OnStart(string[] args)
        {
            threadForm =new Thread(new ThreadStart(FormShow));
            threadForm.Start();
        }

        ///
        /// 停止此服务。
        ///
protectedoverridevoid OnStop()
        {
            if (threadForm !=null)
            {
                if (threadForm.IsAlive)
                {
                    threadForm.Abort();
                    threadForm =null;
                }
            }
        }

        void FormShow()
        {

            GetDesktopWindow();
            IntPtr hwinstaSave = GetProcessWindowStation();
            IntPtr dwThreadId = GetCurrentThreadId();
            IntPtr hdeskSave = GetThreadDesktop(dwThreadId);
            IntPtr hwinstaUser = OpenWindowStation("WinSta0", false, 33554432);
            if (hwinstaUser == IntPtr.Zero)
            {
                RpcRevertToSelf();
                return;
            }
            SetProcessWindowStation(hwinstaUser);
            IntPtr hdeskUser = OpenDesktop("Default", 0, false, 33554432);
            RpcRevertToSelf();
            if (hdeskUser == IntPtr.Zero)
            {
                SetProcessWindowStation(hwinstaSave);
                CloseWindowStation(hwinstaUser);
                return;
            }
            SetThreadDesktop(hdeskUser);

            IntPtr dwGuiThreadId = dwThreadId;

            Form1 f =new Form1(); //此FORM1可以带notifyIcon,可以显示在托盘里,用户可点击托盘图标进行设置
            System.Windows.Forms.Application.Run(f);


            dwGuiThreadId = IntPtr.Zero;
            SetThreadDesktop(hdeskSave);
            SetProcessWindowStation(hwinstaSave);
            CloseDesktop(hdeskUser);
            CloseWindowStation(hwinstaUser);
        }

        [DllImport("user32.dll")]
        staticexternint GetDesktopWindow();

        [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 a);

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

更多精彩内容其他人还在看

asp.net 页面间传值与跳转的区别

通过Server.Transfer("b.aspx") 与Response.Redirect("b.aspx")的区别
收藏 0 赞 0 分享

ASP.NET Gridview与checkbox全选、全不选实现代码

ASP.NET Gridview checkbox全选与全不选实现代码,其实原理就是利用js来实现的,但需要简单的设置下回传。
收藏 0 赞 0 分享

ASP.NET DropDownList控件的使用方法

ASP.NET DropDownList控件的使用方法,学习asp.net的朋友没用过这个控件的朋友可以参考下。
收藏 0 赞 0 分享

一些.NET对多线程异常处理技巧分享

多线程应用,在实际的项目或产品开发中,原则上来说,应该尽量避免,但是在强调用户体验的要求下或开发平台的限制下(如 Silverlight Socket 通讯),我们不得不用多线程。
收藏 0 赞 0 分享

ASP.NET MVC运行出现Uncaught TypeError: Cannot set property __MVC_FormValidation of null的解决方法

同一相站点,有些页面的客户端验证能工作,而有些死活不行。打开页面就出现Uncaught TypeError: Cannot set property __MVC_FormValidation of null错误
收藏 0 赞 0 分享

asp.net 通用分页显示辅助类(改进版)

在使用ASP.NET编程时,如果不用控件的默认分页功能,想自己搞一个,可以看看本文的asp.net通用分页显示辅助类哦。
收藏 0 赞 0 分享

微软 Visual Studio 2010官方下载地址给大家

昨天VS2010在网上报道都已经发布了,现在今天在网上找到Visual Studio 2010官方下载地址,提供给大家下载。
收藏 0 赞 0 分享

Javascript 直接调用服务器C#代码 ASP.NET Ajax实例

近来总有一些朋友会问到一些入门的问题,把这些问题整理一下,写出来。在以前的文章里,曾经利用纯JS编写过Ajax引擎,在真正开发的时候,大家都不喜欢以这种低效率的方式开发,利用MS Ajax的集成的引擎,可以简单不少工作。
收藏 0 赞 0 分享

ASP.NET 页面刷新的实现方法(包括html,js)

ASP.NET 页面刷新的实现方法,比较全了, 包括html与js下的实现方法。
收藏 0 赞 0 分享

asp.net 无刷新翻页就是这么简单

前两天看了一个自定义分页控件,和AspNetPager一样是实现IPostBackEventHandler接口,不过简洁许多,就想能不能实现ICallbackEventHandler接口做到无刷新分页呢?想到了就马上去做,终于,设想变成了现实!!
收藏 0 赞 0 分享
查看更多