實現可互動的WINDOWS服務

來源:互聯網
上載者:User

這幾天想做個檔案監控服務,看了一下網上的關於WINDOWS服務的文章,數量都不少,都只講了如何做一個最基本的服務,卻沒有講述如何與使用者進行互動。查看了MSDN,看一下關於服務的描述:

Windows 服務應用程式在不同於登入使用者的互動地區的視窗地區中運行。視窗地區是包含剪貼簿、一組全域原子和一組案頭對象的安全性實體。由於 Windows 服務的地區不是互動地區,因此 Windows 服務應用程式中引發的對話方塊將是不可見的,並且可能導致程式停止回應。同樣,錯誤資訊應記錄在 Windows 事件記錄中,而不是在使用者介面中引發。

.NET Framework 支援的 Windows 服務類不支援與互動地區(即登入使用者)進行互動。同時,.NET Framework 不包含表示地區和案頭的類。如果 Windows 服務必須與其他地區進行互動,則需要訪問非託管的 Windows API。

也就是說我們要實現可互動的服務(比如我們想給服務在運行時做一些參數設定等),那我們一定要using System.Runtime.InteropServices 

那麼來看一下如果才能實現一個可互動的服務呢。步驟與實現基本的服務一樣(各位可自行參考MSDN或網上google一下).

在實現OnStart時要注意,這裡可不能彈出一個FORM什麼的。這樣做是沒有任何反應的。我們可以在這個方法裡運行一個線程。該線程需要訪問視窗地區對象或案頭對象,當然 framework裡是沒有提供這些的,要訪問Unmanaged 程式碼的。

來看一下代碼,再運行試一下。

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
{
 public class Service1 : System.ServiceProcess.ServiceBase
 {
  /// <summary>
  /// 必需的設計器變數。
  /// </summary>
  private System.ComponentModel.Container components = null;
  Thread threadForm=null;
  public Service1()
  {
   // 該調用是 Windows.Forms 組件設計器所必需的。
   InitializeComponent();

   // TODO: 在 InitComponent 調用後添加任何初始化
  }

  #region 組件設計器產生的程式碼
  /// <summary>
  /// 設計器支援所需的方法 - 不要使用代碼編輯器
  /// 修改此方法的內容。
  /// </summary>
  private void InitializeComponent()
  {
   //
   // Service1
   //
   this.ServiceName = "JadeWatchService";

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

  }
  /// <summary>
  /// 清理所有正在使用的資源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  /// <summary>
  /// 設定具體的操作,以便服務可以執行它的工作。
  /// </summary>
  protected override void OnStart(string[] args)
  {
   threadForm=new Thread(new ThreadStart(FormShow));
   threadForm.Start();
  }
 
  /// <summary>
  /// 停止此服務。
  /// </summary>
  protected override void 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")]
  static extern int GetDesktopWindow();

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

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

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

  [DllImport("user32.dll")]
  static extern IntPtr OpenWindowStation(string a,bool b,int c);

  [DllImport("user32.dll")]
  static extern IntPtr OpenDesktop(string lpszDesktop, uint dwFlags,
   bool fInherit, uint dwDesiredAccess);

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

  [DllImport("rpcrt4.dll", SetLastError=true)]
  static extern IntPtr RpcImpersonateClient(int i);

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

  [DllImport("user32.dll")]
  static extern IntPtr SetThreadDesktop(IntPtr a);

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.