C#服务获取不了当前激活窗口句柄
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]public static extern IntPtr GetForegroundWindow();//获取当前激活窗口//获取窗口标题[DllImport("user32", SetLastError = true)]public static extern int GetWindowText(IntPtr hWnd, //窗口句柄StringBuilder lpString, //标题int nMaxCount //最大值);//获取类的名字[DllImport("user32.dll")]private static extern int GetClassName( IntPtr hWnd, //句柄 StringBuilder lpString, //类名 int nMaxCount //最大值);[DllImport("user32.dll")][return: MarshalAs(UnmanagedType.Bool)]static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);private void getAllProcess(object sender, ElapsedEventArgs e) { allprocess = Process.GetProcesses(); foreach (Process pro in allprocess) { string pName = pro.ProcessName; if (pName == "QQ") { try { IntPtr formHandle = GetForegroundWindow(); StringBuilder title = new StringBuilder(256); GetWindowText(formHandle, title, title.Capacity);//得到窗口的标题 StringBuilder className = new StringBuilder(256); GetClassName(formHandle, className, className.Capacity);//得到窗口的句柄 RECT rc = new RECT(); GetWindowRect(formHandle, ref rc); string formName = className.ToString(); string fileSavePath = @"D:\image\qqimage/"; publicDll.logMsg("QQ:开始查找 " + className, logMsgType.Normal); publicDll.logMsg("QQ:是否截图 " + title, logMsgType.Normal); if (formName.EndsWith("TXGuiFoundation")) { publicDll.logMsg("TXGuiFoundation:" + pName, logMsgType.Normal); if (!System.IO.Directory.Exists(fileSavePath)) { System.IO.Directory.CreateDirectory(fileSavePath); } GetImageFromScreen();//截图 } } catch (Exception ex) { publicDll.logMsg("Error:" + ex.Message, logMsgType.Normal); } } } }
using System;using System.Runtime.InteropServices;using System.ServiceProcess;using System.Text;using System.Threading;namespace WindowsService1{ public partial class Service1 : ServiceBase { private Boolean _bStart; [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();//获取当前激活窗口 //获取窗口标题 [DllImport("user32", SetLastError = true)] public static extern int GetWindowText( IntPtr hWnd, //窗口句柄 StringBuilder lpString, //标题 int nMaxCount //最大值 ); //获取类的名字 [DllImport("user32.dll")] private static extern int GetClassName( IntPtr hWnd, //句柄 StringBuilder lpString, //类名 int nMaxCount //最大值 ); public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { _bStart = true; ThreadPool.QueueUserWorkItem(new WaitCallback((obj) => { IntPtr curHwnd = IntPtr.Zero; IntPtr lastHwnd = IntPtr.Zero; while (_bStart) { curHwnd = GetForegroundWindow(); if (curHwnd != IntPtr.Zero && curHwnd != lastHwnd) { lastHwnd = curHwnd; StringBuilder sb = new StringBuilder(255); GetWindowText(curHwnd, sb, 255); if (sb.Length > 0) { System.IO.File.AppendAllText("c:\\log.txt", String.Format("{0}\r\n", sb.ToString())); } } } } ), null); } protected override void OnStop() { _bStart = false; } }}