代码改变世界

Windows Service下的MessageBox

2009-09-12 14:25  Franz  阅读(907)  评论(0编辑  收藏  举报

因为项目的原因今天又搞起了Windows service,由于项目的需求要在windows下show一个messageBox出来.我记得以前曾经搞过,拍胸脯说Ok,这个好办.

我记得windows service call一下win32的MessageBox就搞定了吧

int MessageBox(      
    HWND hWnd,     LPCTSTR lpText,     LPCTSTR lpCaption,     UINT uType );
 

DllImport一下,咦,没有反应.囧

查了一下才知道,这个方式在visit之后就不好使了.我们可以通过WTTSendMessage来发送消息.

BOOL WTSSendMessage(
  __in   HANDLE hServer,
  __in   DWORD SessionId,
  __in   LPTSTR pTitle,
  __in   DWORD TitleLength,
  __in   LPTSTR pMessage,
  __in   DWORD MessageLength,
  __in   DWORD Style,
  __in   DWORD Timeout,
  __out  DWORD *pResponse,
  __in   BOOL bWait
);

安装国际惯例我们包一层供别人更好的使用

 

 1public class MessageBox 
 2
 3    private static IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero; 
 4    private static int WTS_CURRENT_SESSION = WTSGetActiveConsoleSessionId(); 
 5    public MessageBoxResult Show(string title, string text, MessageBoxButtons messageBoxButtons) 
 6    
 7        var style = (int)messageBoxButtons; 
 8        int resp = 0
 9
10        var result = WTSSendMessage(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, title, title.Length, text, 
11                                    text.Length, style, 0out resp, true); 
12        int error = Marshal.GetLastWin32Error(); 
13        Marshal.ThrowExceptionForHR(error); 
14        return (MessageBoxResult)resp; 
15    }
 
16
17    [DllImport("kernel32.dll")] 
18    static extern int WTSGetActiveConsoleSessionId(); 
19
20    [DllImport("wtsapi32.dll", SetLastError = true)] 
21    static extern bool WTSSendMessage( 
22                IntPtr hServer, 
23                [MarshalAs(UnmanagedType.I4)] int SessionId, 
24                String pTitle, 
25                [MarshalAs(UnmanagedType.U4)] int TitleLength, 
26                String pMessage, 
27                [MarshalAs(UnmanagedType.U4)] int MessageLength, 
28                [MarshalAs(UnmanagedType.U4)] int Style, 
29                [MarshalAs(UnmanagedType.U4)] int Timeout, 
30                [MarshalAs(UnmanagedType.U4)] out int pResponse, 
31                bool bWait); 
32
33}
 
34
35public enum MessageBoxResult 
36
37    None, 
38    OK, 
39    Cancel, 
40    Abort, 
41    Retry, 
42    Ignore, 
43    Yes, 
44    No 
45}
 
46
47public enum MessageBoxButtons 
48
49    OK, 
50    OKCancel, 
51    AbortRetryIgnore, 
52    YesNoCancel, 
53    YesNo, 
54    RetryCancel 
55}

56
57

 

使用方法和普通的messagebox没有多少区别,Show方法可以根据自己的喜好重载一下咯,我就不糊代码了!

 

参考:

http://blogs.msdn.com/yvesdolc/archive/2009/08/20/do-you-still-use-the-messagebox-api-in-your-windows-service.aspx

http://msdn.microsoft.com/en-us/library/aa383842(VS.85).aspx

http://www.pinvoke.net/default.aspx/wtsapi32/WTSSendMessage.html