private static void Main(string[] args) { TargetConfig config = null; Console.Title = "TeamViewer弹框自动检测程序,请勿关闭。"; Console.WriteLine("TeamViewer弹框自动检测程序。TeamViewer Popup Window Auto Detector."); Console.WriteLine("按 Ctrl + C 关闭。 Press Ctrl + C to quit."); #region Read configuration // Read configuration try { var configContent = System.IO.File.ReadAllText(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "tar.json"); config = Newtonsoft.Json.JsonConvert.DeserializeObject <TargetConfig>(configContent); if (config == null) { throw new Exception("找不到配置文件"); } if (config.Targets == null || config.Targets.Length == 0) { throw new Exception("配置文件中不包含目标窗口项。"); } } catch (Exception ex) { Console.Error.WriteLine("读取配置文件失败:" + ex.ToString()); return; // throw; } #endregion Read configuration #region Begin detect // Begin detect while (true) { WindowFinder.Detect(config, PROCESS_NAME, (proc, hParenWnd, hWnd) => { Console.WriteLine("已经找到目标窗口,发送关闭消息! Target located. Sending WM_CLOSE message. "); NativeMethods.SendMessage(hParenWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); return(true); }); System.Threading.Thread.Sleep(DETECT_INTERVAL); } #endregion Begin detect }
public static void Detect(TargetConfig config, string exeName, Func <System.Diagnostics.Process, IntPtr, IntPtr, bool> onSuccess) { if (NativeMethods.AnyPopup() == 0) { return; } //Imports.EnumWindows(new CallBack((hwnd,lPram)=> { // return true; //}, 0); NativeMethods.EnumWindows((hwnd, lPram) => { NativeMethods.GetWindowThreadProcessId(hwnd, out int pId); if (pId > 0) { var proc = System.Diagnostics.Process.GetProcessById(pId); if (proc != null) { try { var moduleName = proc.MainModule.ModuleName; if (moduleName.Equals(exeName, StringComparison.OrdinalIgnoreCase)) { var procWinTitle = proc.MainWindowTitle; // Match main window var matchCfg = config.Targets.Where(cfg => { if (string.IsNullOrEmpty(cfg.WindowTitle)) { return(true); } if (cfg.TitleContains) { return(procWinTitle.IndexOf(cfg.WindowTitle, StringComparison.OrdinalIgnoreCase) >= 0); } else { return(procWinTitle.Equals(cfg.WindowTitle, StringComparison.OrdinalIgnoreCase)); } }).FirstOrDefault(); // find child window (buttons & labels & links ... ) if (matchCfg != null) { NativeMethods.EnumChildWindows(hwnd, (hChildWin, lparam) => { var title = new StringBuilder(1000); if (NativeMethods.GetWindowText(hChildWin, title, 1000) != 0) { var winTitle = title.ToString(); if (winTitle.Equals(matchCfg.ChildText, StringComparison.OrdinalIgnoreCase)) { if (onSuccess != null) { onSuccess.Invoke(proc, hwnd, hChildWin); } return(false); } } return(true); }, IntPtr.Zero); } } } catch (Exception) { // Console.WriteLine(proc.ProcessName + ": " + ex.Message); // throw; } } } return(true); }, IntPtr.Zero); }