public override void Start() { try { // Register for Window Events _dele = new NativeMethods.WinEventDelegate(WinEventProc); _hWinEventHookForWindowSwitch = NativeMethods.SetWinEventHook(NativeMethods.EVENT_SYSTEM_FOREGROUND, NativeMethods.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _dele, 0, 0, NativeMethods.WINEVENT_OUTOFCONTEXT); _hWinEventHookForWindowTitleChange = NativeMethods.SetWinEventHook(NativeMethods.EVENT_OBJECT_NAMECHANGE, NativeMethods.EVENT_OBJECT_NAMECHANGE, IntPtr.Zero, _dele, 0, 0, NativeMethods.WINEVENT_OUTOFCONTEXT); // Register to check if idle or not if (Settings.RecordIdle) { if (_idleCheckTimer != null) Stop(); _idleCheckTimer = new Timer(); _idleCheckTimer.Interval = Settings.IdleTimerIntervalInMilliseconds; _idleCheckTimer.Elapsed += CheckIfIdleTime; _idleCheckTimer.Start(); _lastInputInfo = new NativeMethods.LASTINPUTINFO(); _lastInputInfo.cbSize = (uint)Marshal.SizeOf(_lastInputInfo); _lastInputInfo.dwTime = 0; } IsRunning = true; } catch (Exception e) { Database.GetInstance().LogWarning("Registering events failed: " + e.Message); IsRunning = false; } }
/// <summary> /// Constructor (Singleton so private) /// </summary> private ProcessesService() { Logger.Instance.Info("Init processes service"); _excludedWindows = new List <IntPtr>(); GetProcesses(); _createDestroyEventProc = CreateDestroyEventProc; _createDestroyEventhook = NativeMethods.SetWinEventHook( (uint)EventConstants.EVENT_OBJECT_CREATE, (uint)EventConstants.EVENT_OBJECT_DESTROY, IntPtr.Zero, _createDestroyEventProc, 0, 0, (uint)EventConstants.WINEVENT_OUTOFCONTEXT | (uint)EventConstants.WINEVENT_SKIPOWNPROCESS ); _foregroundEventProc = ForegroundEventProc; _foregroundEventhook = NativeMethods.SetWinEventHook( (uint)EventConstants.EVENT_SYSTEM_FOREGROUND, (uint)EventConstants.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _foregroundEventProc, 0, 0, (uint)EventConstants.WINEVENT_OUTOFCONTEXT | (uint)EventConstants.WINEVENT_SKIPOWNPROCESS ); }
public ActiveWindowHook() { _hookDelegate = WinEventProc; _hookHandleWinChange = NativeMethods.SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _hookDelegate, 0, 0, WINEVENT_OUTOFCONTEXT); if (_hookHandleWinChange == IntPtr.Zero) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. var errorCode = Marshal.GetLastWin32Error(); //do cleanup //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } _hookHandleTitleChange = NativeMethods.SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, IntPtr.Zero, _hookDelegate, 0, 0, WINEVENT_OUTOFCONTEXT); if (_hookHandleTitleChange == IntPtr.Zero) { //Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set. var errorCode = Marshal.GetLastWin32Error(); //do cleanup //Initializes and throws a new instance of the Win32Exception class with the specified error. throw new Win32Exception(errorCode); } }
public static void AddHook() { _winEventDelegate = WinEventProc; m_hhook = NativeMethods.SetWinEventHook(NativeMethods.EVENT_SYSTEM_FOREGROUND, NativeMethods.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _winEventDelegate, 0, 0, NativeMethods.WINEVENT_OUTOFCONTEXT); }
public GlobalWindowEvents() { uint eventMin = (uint)NativeMethods.WinEvents.EVENT_SYSTEM_SWITCHSTART; uint eventMax = (uint)NativeMethods.WinEvents.EVENT_SYSTEM_SWITCHEND; lpfnWinEventProc = new NativeMethods.WinEventDelegate(WinEventProc); this.m_hWinEventHook = NativeMethods.SetWinEventHook(eventMin, eventMax, IntPtr.Zero, lpfnWinEventProc, 0, 0, NativeMethods.WINEVENT_OUTOFCONTEXT); }
public static void AddHook() { _winEventDelegate = WinEventProc; m_hhook = NativeMethods.SetWinEventHook(NativeMethods.EVENT_SYSTEM_FOREGROUND, NativeMethods.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _winEventDelegate, 0, 0, NativeMethods.WINEVENT_OUTOFCONTEXT); }
public GlobalWindowEvents() { uint eventMin = (uint)NativeMethods.WinEvents.EVENT_SYSTEM_SWITCHSTART; uint eventMax = (uint)NativeMethods.WinEvents.EVENT_SYSTEM_SWITCHEND; lpfnWinEventProc = new NativeMethods.WinEventDelegate(WinEventProc); this.m_hWinEventHook = NativeMethods.SetWinEventHook(eventMin, eventMax, IntPtr.Zero, lpfnWinEventProc, 0, 0, NativeMethods.WINEVENT_OUTOFCONTEXT); }
public void Init() { processHook = new NativeMethods.WinEventDelegate(WinEventProc); NativeMethods.dele += processHook; NativeMethods.SetHook(); // Init ColorController cController.Init(); }
public void Run() { _windowEventDelegate = WinEventProc; var hooked = _nativeMethods.SetWinEventHook( NativeMethods.EVENT_SYSTEM_FOREGROUND, NativeMethods.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _windowEventDelegate, 0, 0, NativeMethods.WINEVENT_OUTOFCONTEXT); }
public override void Start() { try { // Register for Window Events _dele = new NativeMethods.WinEventDelegate(WinEventProc); _hWinEventHookForWindowSwitch = NativeMethods.SetWinEventHook(NativeMethods.EVENT_SYSTEM_FOREGROUND, NativeMethods.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, _dele, 0, 0, NativeMethods.WINEVENT_OUTOFCONTEXT); _hWinEventHookForWindowTitleChange = NativeMethods.SetWinEventHook(NativeMethods.EVENT_OBJECT_NAMECHANGE, NativeMethods.EVENT_OBJECT_NAMECHANGE, IntPtr.Zero, _dele, 0, 0, NativeMethods.WINEVENT_OUTOFCONTEXT); // Register for logout/shutdown event SystemEvents.SessionEnding += SessionEnding; SystemEvents.PowerModeChanged += OnPowerChange; // Register to check if idle or not if (Settings.RecordIdle) { // reset everything properly if (_idleCheckTimer != null || _idleSleepValidator != null) { Stop(); } // register for events _idleCheckTimer = new Timer(); _idleCheckTimer.Interval = Settings.IdleTimerInterval_ms; _idleCheckTimer.Elapsed += CheckIfIdleTime; _idleCheckTimer.Start(); _idleSleepValidator = new Timer(); _idleSleepValidator.Interval = Settings.IdleSleepValidate_TimerInterval_ms; _idleSleepValidator.Elapsed += ValidateSleepIdleTime; _idleSleepValidator.Start(); _lastInputInfo = new NativeMethods.LASTINPUTINFO(); _lastInputInfo.cbSize = (uint)Marshal.SizeOf(_lastInputInfo); _lastInputInfo.dwTime = 0; } IsRunning = true; } catch (Exception e) { Database.GetInstance().LogWarning("Registering events failed: " + e.Message); IsRunning = false; } }
public IntPtr SetWinEventHook( uint eventMin, uint eventMax, IntPtr hmodWinEventProc, NativeMethods.WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags) { return(NativeMethods.SetWinEventHook( eventMin, eventMax, hmodWinEventProc, lpfnWinEventProc, idProcess, idThread, dwFlags)); }
public MainWindow() { Instance = this; InitializeComponent(); var helper = new WindowInteropHelper(this); helper.EnsureHandle(); this.m_handle = helper.Handle; this.m_hookProc = new NativeMethods.WinEventDelegate(this.WinEventProc); this.ctlFilter.ItemsSource = ChatType.Types.Values; this.m_chat = CollectionViewSource.GetDefaultView(Worker.ChatLog); this.m_chat.Filter = (e) => ((Chat)e).ChatType.Visible; this.ctlList.ItemsSource = m_chat; }
private void AttachToWindow() { if (this.m_AppWin != IntPtr.Zero) { // Set the application as a child of the parent form NativeMethods.SetParent(m_AppWin, this.Handle); // Show it! (must be done before we set the windows visibility parameters below NativeMethods.ShowWindow(m_AppWin, NativeMethods.WindowShowStyle.Maximize); // set window parameters (how it's displayed) long lStyle = NativeMethods.GetWindowLong(m_AppWin, NativeMethods.GWL_STYLE); lStyle &= ~NativeMethods.WS_BORDER; if (this.proto == SuperPutty.Data.ConnectionProtocol.VNC) { lStyle |= NativeMethods.WS_HSCROLL | NativeMethods.WS_VSCROLL; } NativeMethods.SetWindowLong(m_AppWin, NativeMethods.GWL_STYLE, lStyle); NativeMethods.WinEventDelegate lpfnWinEventProc = new NativeMethods.WinEventDelegate(WinEventProc); this.lpfnWinEventProcs.Add(lpfnWinEventProc); uint eventType = (uint)NativeMethods.WinEvents.EVENT_OBJECT_NAMECHANGE; this.m_hWinEventHooks.Add(NativeMethods.SetWinEventHook(eventType, eventType, IntPtr.Zero, lpfnWinEventProc, (uint)m_Process.Id, 0, NativeMethods.WINEVENT_OUTOFCONTEXT)); if ((lStyle & NativeMethods.WS_DLGFRAME) == 0) { eventType = (uint)NativeMethods.WinEvents.EVENT_SYSTEM_FOREGROUND; this.m_hWinEventHooks.Add(NativeMethods.SetWinEventHook(eventType, eventType, IntPtr.Zero, lpfnWinEventProc, (uint)m_Process.Id, 0, NativeMethods.WINEVENT_OUTOFCONTEXT)); } } else { MessageBox.Show("Process window not found.", "Process Window Not Found"); try { m_Process.Kill(); } catch (InvalidOperationException ex) { Log.WarnFormat("no process window found to kill: {0}", ex.Message); } return; } }
public static void init() { if (!rtssInstalled()) { Log.Error("RTSS no está instalado en este equipo"); return; } if (!isRTSSRunning()) { startRTSS(); } Log.Info("Conectando a la memoria compartida de RTSS..."); int r = NativeMethods.rtssMain(); if (r >= 0) { Log.Info("Mapeado a la memoria correcto. RTSS " + (r >> 16) + "." + (r & 0x0000FFFF)); } else { Log.Error("No se puede conectar a la memoria compartida de RTSS"); return; } setForegroundAppThread(); ///// wed = new NativeMethods.WinEventDelegate(WinEventProc); m_hook = NativeMethods.SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, wed, 0, 0, WINEVENT_OUTOFCONTEXT); Log.Info("RTSS iniciado correctamente."); GC.Collect(); Program.componentLoaded(); }
public static extern IntPtr SetWinEventHook(NativeMethods.SWEH_Events eventMin, NativeMethods.SWEH_Events eventMax, IntPtr hmodWinEventProc, NativeMethods.WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, NativeMethods.SWEH_dwFlags dwFlags);
internal Windawesome() { applications = new Dictionary<IntPtr, LinkedList<Tuple<Workspace, Window>>>(20); hiddenApplications = new HashMultiSet<IntPtr>(); messageHandlers = new Dictionary<int, HandleMessageDelegate>(2); monitors = Screen.AllScreens.Select((_, i) => new Monitor(i)).ToArray(); this.CreateHandle(new CreateParams { Parent = NativeMethods.HWND_MESSAGE, ClassName = "Message" }); HandleStatic = this.Handle; config = new Config(); config.LoadConfiguration(this); var startingWorkspacesCount = config.StartingWorkspaces.Count(); var distinctStartingWorkspaceMonitorsCount = config.StartingWorkspaces.Select(w => w.Monitor).Distinct().Count(); if (distinctStartingWorkspaceMonitorsCount != monitors.Length || distinctStartingWorkspaceMonitorsCount != startingWorkspacesCount) { throw new Exception("Each Monitor should have exactly one corresponding Workspace in StartingWorkspaces, i.e. " + "you should have as many Workspaces in StartingWorkspaces as you have Monitors!"); } CurrentWorkspace = config.StartingWorkspaces.First(w => w.Monitor.screen.Primary); topmostWindows = new WindowBase[config.Workspaces.Length]; Workspace.WindowActivatedEvent += h => topmostWindows[CurrentWorkspace.id - 1] = CurrentWorkspace.GetWindow(h) ?? new WindowBase(h); // add workspaces to their corresponding monitors monitors.ForEach(m => config.Workspaces.Where(w => w.Monitor == m).ForEach(m.AddWorkspace)); // n ^ 2 but hopefully fast enough // set starting workspaces for each monitor config.StartingWorkspaces.ForEach(w => w.Monitor.SetStartingWorkspace(w)); // initialize bars and plugins config.Bars.ForEach(b => b.InitializeBar(this)); config.Plugins.ForEach(p => p.InitializePlugin(this)); // add all windows to their respective workspaces NativeMethods.EnumWindows((hWnd, _) => (Utilities.IsAppWindow(hWnd) && AddWindowToWorkspace(hWnd, finishedInitializing: false)) || true, IntPtr.Zero); // add a handler for when the working area or screen rosolution changes as well as // a handler for the system shutting down/restarting SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged; SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged; SystemEvents.SessionEnding += OnSessionEnding; SystemSettingsChanger.ApplyChanges(config); // initialize all workspaces and hide windows not on StartingWorkspaces var windowsToHide = new HashSet<Window>(); foreach (var workspace in config.Workspaces) { workspace.GetWindows().ForEach(w => windowsToHide.Add(w)); workspace.Initialize(); topmostWindows[workspace.id - 1] = workspace.GetWindows().FirstOrDefault(w => !NativeMethods.IsIconic(w.hWnd)) ?? new WindowBase(NativeMethods.shellWindow); } windowsToHide.ExceptWith(config.StartingWorkspaces.SelectMany(ws => ws.GetWindows())); var winPosInfo = NativeMethods.BeginDeferWindowPos(windowsToHide.Count); winPosInfo = windowsToHide.Where(Utilities.WindowIsNotHung).Aggregate(winPosInfo, (current, w) => NativeMethods.DeferWindowPos(current, w.hWnd, IntPtr.Zero, 0, 0, 0, 0, NativeMethods.SWP.SWP_NOACTIVATE | NativeMethods.SWP.SWP_NOMOVE | NativeMethods.SWP.SWP_NOSIZE | NativeMethods.SWP.SWP_NOZORDER | NativeMethods.SWP.SWP_NOOWNERZORDER | NativeMethods.SWP.SWP_HIDEWINDOW)); NativeMethods.EndDeferWindowPos(winPosInfo); // remove windows from ALT-TAB menu and Taskbar config.StartingWorkspaces.Where(ws => ws != CurrentWorkspace).SelectMany(ws => ws.GetWindows()). Where(w => w.hideFromAltTabAndTaskbarWhenOnInactiveWorkspace).ForEach(w => w.ShowInAltTabAndTaskbar(false)); // initialize monitors and switch to the default starting workspaces monitors.ForEach(m => m.Initialize()); Monitor.ShowHideWindowsTaskbar(CurrentWorkspace.ShowWindowsTaskbar); DoForTopmostWindowForWorkspace(CurrentWorkspace, ActivateWindow); CurrentWorkspace.IsCurrentWorkspace = true; // register a shell hook NativeMethods.RegisterShellHookWindow(this.Handle); currentActiveWindow = NativeMethods.GetForegroundWindow(); // register some shell events winEventDelegate = WinEventDelegate; windowDestroyedShownOrHiddenWinEventHook = NativeMethods.SetWinEventHook(NativeMethods.EVENT.EVENT_OBJECT_DESTROY, NativeMethods.EVENT.EVENT_OBJECT_HIDE, IntPtr.Zero, winEventDelegate, 0, 0, NativeMethods.WINEVENT.WINEVENT_OUTOFCONTEXT | NativeMethods.WINEVENT.WINEVENT_SKIPOWNTHREAD); windowMinimizedOrRestoredWinEventHook = NativeMethods.SetWinEventHook(NativeMethods.EVENT.EVENT_SYSTEM_MINIMIZESTART, NativeMethods.EVENT.EVENT_SYSTEM_MINIMIZEEND, IntPtr.Zero, winEventDelegate, 0, 0, NativeMethods.WINEVENT.WINEVENT_OUTOFCONTEXT | NativeMethods.WINEVENT.WINEVENT_SKIPOWNTHREAD); windowFocusedWinEventHook = NativeMethods.SetWinEventHook(NativeMethods.EVENT.EVENT_SYSTEM_FOREGROUND, NativeMethods.EVENT.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, winEventDelegate, 0, 0, NativeMethods.WINEVENT.WINEVENT_OUTOFCONTEXT | NativeMethods.WINEVENT.WINEVENT_SKIPOWNTHREAD); if (config.CheckForUpdates) { UpdateChecker.CheckForUpdate(); } }
public Form1() { InitializeComponent(); this.m_delegate = new NativeMethods.WinEventDelegate(this.WinEventProc); }
public ApplicationPanel() { this.Disposed += new EventHandler(ApplicationPanel_Disposed); SuperPuTTY.LayoutChanged += new EventHandler<Data.LayoutChangedEventArgs>(SuperPuTTY_LayoutChanged); // setup up the hook to watch for all EVENT_SYSTEM_FOREGROUND events system wide string typeName = string.IsNullOrEmpty(SuperPuTTY.Settings.WindowActivator) ? ActivatorTypeName : SuperPuTTY.Settings.WindowActivator; this.m_windowActivator = (WindowActivator)Activator.CreateInstance(Type.GetType(typeName)); //this.m_windowActivator = new SetFGCombinedWindowActivator(); this.m_winEventDelegate = new NativeMethods.WinEventDelegate(WinEventProc); this.m_hWinEventHook = NativeMethods.SetWinEventHook( (int) NativeMethods.WinEvents.EVENT_SYSTEM_FOREGROUND, (int) NativeMethods.WinEvents.EVENT_OBJECT_NAMECHANGE, IntPtr.Zero, this.m_winEventDelegate, 0, 0, NativeMethods.WINEVENT_OUTOFCONTEXT); SuperPuTTY.Settings.SettingsSaving += Settings_SettingsSaving; }
public frmMain() { InitializeComponent(); this.m_hookProc = new NativeMethods.WinEventDelegate(this.WinEventProc); }
/// <summary> /// Create (start) the hosted application when the parent becomes visible /// </summary> /// <param name="e">Not used</param> protected override void OnVisibleChanged(EventArgs e) { if (!m_Created && !String.IsNullOrEmpty(ApplicationName)) // only allow one instance of the child { m_Created = true; m_AppWin = IntPtr.Zero; try { if(!File.Exists(ApplicationName)) { MessageBox.Show("putty.exe not found in configured path, please go into tools->settings and set the correct path", "Application Not Found"); return; } m_Process = new Process { EnableRaisingEvents = true, StartInfo = { FileName = ApplicationName, Arguments = ApplicationParameters } }; //m_Process.Exited += new EventHandler(p_Exited); if (!string.IsNullOrEmpty(this.ApplicationWorkingDirectory) && Directory.Exists(this.ApplicationWorkingDirectory)) { m_Process.StartInfo.WorkingDirectory = this.ApplicationWorkingDirectory; } m_Process.Exited += delegate { m_CloseCallback(true); }; m_Process.Start(); // Wait for application to start and become idle m_Process.WaitForInputIdle(); m_AppWin = m_Process.MainWindowHandle; if (IntPtr.Zero == m_AppWin) { Log.WarnFormat("Unable to get handle for process on first try.{0}", LoopWaitForHandle ? " Polling 10 s for handle." : ""); if (LoopWaitForHandle) { DateTime startTime = DateTime.Now; while ((DateTime.Now - startTime).TotalSeconds < 10) { System.Threading.Thread.Sleep(50); // Refresh Process object's view of real process m_Process.Refresh(); m_AppWin = m_Process.MainWindowHandle; if (IntPtr.Zero != m_AppWin) { Log.Info("Successfully found handle via polling " + (DateTime.Now - startTime).TotalMilliseconds + " ms"); break; } } } } } catch (InvalidOperationException ex) { /* Possible Causes: * No file name was specified in the Process component's StartInfo. * -or- * The ProcessStartInfo.UseShellExecute member of the StartInfo property is true while ProcessStartInfo.RedirectStandardInput, * ProcessStartInfo.RedirectStandardOutput, or ProcessStartInfo.RedirectStandardError is true. */ MessageBox.Show(this, ex.Message, "Invalid Operation Error"); throw; } catch (Win32Exception ex) { /* * Checks are elsewhere to ensure these don't occur, but incase they do we're gonna bail with a nasty exception * which will hopefully send users kicking and screaming at me to fix this (And hopefully they will include a * stacktrace!) */ if (ex.NativeErrorCode == NativeMethods.ERROR_ACCESS_DENIED) { throw; } else if (ex.NativeErrorCode == NativeMethods.ERROR_FILE_NOT_FOUND) { throw; } } if (SuperPuTTY.PuTTYAppName + " Command Line Error" == this.m_Process.MainWindowTitle) { // dont' try to capture or manipulate the window Log.WarnFormat("Error while creating putty session: title={0}, handle={1}. Abort capture window", this.m_Process.MainWindowTitle, this.m_AppWin); MessageBox.Show("Could not start putty session: Arguments passed to commandline invalid.", "putty command line error."); this.m_AppWin = IntPtr.Zero; } if(this.m_AppWin != IntPtr.Zero) { // Set the application as a child of the parent form NativeMethods.SetParent(m_AppWin, this.Handle); // Show it! (must be done before we set the windows visibility parameters below NativeMethods.ShowWindow(m_AppWin, NativeMethods.WindowShowStyle.Maximize); // set window parameters (how it's displayed) long lStyle = NativeMethods.GetWindowLong(m_AppWin, NativeMethods.GWL_STYLE); lStyle &= ~(NativeMethods.WS_BORDER | NativeMethods.WS_THICKFRAME); NativeMethods.SetWindowLong(m_AppWin, NativeMethods.GWL_STYLE, lStyle); NativeMethods.WinEventDelegate lpfnWinEventProc = new NativeMethods.WinEventDelegate(WinEventProc); this.lpfnWinEventProcs.Add(lpfnWinEventProc); uint eventType = (uint)NativeMethods.WinEvents.EVENT_OBJECT_NAMECHANGE; this.m_hWinEventHooks.Add(NativeMethods.SetWinEventHook(eventType, eventType, IntPtr.Zero, lpfnWinEventProc, (uint)m_Process.Id, 0, NativeMethods.WINEVENT_OUTOFCONTEXT)); eventType = (uint)NativeMethods.WinEvents.EVENT_SYSTEM_FOREGROUND; this.m_hWinEventHooks.Add(NativeMethods.SetWinEventHook(eventType, eventType, IntPtr.Zero, lpfnWinEventProc, (uint)m_Process.Id, 0, NativeMethods.WINEVENT_OUTOFCONTEXT)); } else { MessageBox.Show("Process window not found.", "Process Window Not Found"); try { m_Process.Kill(); } catch (InvalidOperationException ex) { Log.WarnFormat("no process window found to kill: {0}", ex.Message); } return; } } if (this.Visible && this.m_Created && this.ExternalProcessCaptured) { // Move the child so it's located over the parent this.MoveWindow("OnVisChanged"); if (RefocusOnVisChanged && NativeMethods.GetForegroundWindow() != this.m_AppWin) { this.BeginInvoke(new MethodInvoker(delegate { this.ReFocusPuTTY("OnVisChanged"); })); } } base.OnVisibleChanged(e); }
public DragWindowHook() { this.EventDelegate = new NativeMethods.WinEventDelegate(this.WinEventProc); }
static AutoHide() { winProc = new NativeMethods.WinEventDelegate(WinEventProc); using (var proc = Process.GetCurrentProcess()) actPid = proc.Id; }
/// <exception cref="InitFailure">Event hook creation failed.</exception> public ActiveAppManager(bool eventhook = true) { ForegroundEventDelegate = new NativeMethods.WinEventDelegate(WinEventProc); if (eventhook) { if (!SetupEventHook()) { throw new InitFailure("Failed to initialize active app manager."); } } // get current window, just in case it's something we're monitoring var hwnd = NativeMethods.GetForegroundWindow(); NativeMethods.GetWindowThreadProcessId(hwnd, out int pid); Foreground = pid; // Console.WriteLine("--- Foreground Process Identifier: " + Foreground); var corecfg = Taskmaster.Config.Load(Taskmaster.coreconfig); bool dirty = false, modified = false; var perfsec = corecfg.Config["Performance"]; Hysterisis = perfsec.GetSetDefault("Foreground hysterisis", 1500, out modified).IntValue.Constrain(0, 30000); perfsec["Foreground hysterisis"].Comment = "In milliseconds, from 0 to 30000. Delay before we inspect foreground app, in case user rapidly swaps apps."; dirty |= modified; var emsec = corecfg.Config["Emergency"]; HangKillTick = emsec.GetSetDefault("Kill hung", 180 * 5, out modified).IntValue.Constrain(0, 60 * 60 * 4); emsec["Hung kill time"].Comment = "Kill the application after this many seconds. 0 disables. Minimum actual kill time is minimize/reduce time + 60."; dirty |= modified; HangMinimizeTick = emsec.GetSetDefault("Hung minimize time", 180, out modified).IntValue.Constrain(0, 60 * 60 * 2); emsec["Hung minimize time"].Comment = "Try to minimize hung app after this many seconds."; dirty |= modified; HangReduceTick = emsec.GetSetDefault("Hung reduce time", 300, out modified).IntValue.Constrain(0, 60 * 60 * 2); emsec["Hung reduce time"].Comment = "Reduce affinity and priority of hung app after this many seconds."; dirty |= modified; int killtickmin = (Math.Max(HangReduceTick, HangMinimizeTick)) + 60; if (HangKillTick > 0 && HangKillTick < killtickmin) { HangKillTick = killtickmin; } if (HangKillTick > 0 || HangReduceTick > 0 || HangMinimizeTick > 0) { var sbs = new System.Text.StringBuilder(); sbs.Append("<Foreground> Hang action timers: "); if (HangMinimizeTick > 0) { sbs.Append("Minimize: ").Append(HangMinimizeTick).Append("s"); if (HangReduceTick > 0 || HangKillTick > 0) { sbs.Append(", "); } } if (HangReduceTick > 0) { sbs.Append("Reduce: ").Append(HangReduceTick).Append("s"); if (HangKillTick > 0) { sbs.Append(", "); } } if (HangKillTick > 0) { sbs.Append("Kill: ").Append(HangKillTick).Append("s"); } Log.Information(sbs.ToString()); sbs.Clear(); sbs = null; } if (dirty) { corecfg.MarkDirty(); } // TODO: Add timer to check foreground app hanging // TODO: Hang check should only take action if user fails to swap apps (e.g. ctrl-alt-esc for taskmanager) // TODO: Hang check should potentially do the following: // Minimize app, Reduce priority, Reduce cores, Kill it hungTimer.Elapsed += HangDetector; hungTimer.Start(); Log.Information("<Foreground> Component loaded."); }
/// <summary> /// Create (start) the hosted application when the parent becomes visible /// </summary> /// <param name="e">Not used</param> protected override void OnVisibleChanged(EventArgs e) { if (!m_Created && !String.IsNullOrEmpty(ApplicationName)) // only allow one instance of the child { m_Created = true; m_AppWin = IntPtr.Zero; try { if (!File.Exists(ApplicationName)) { MessageBox.Show("putty.exe not found in configured path, please go into tools->settings and set the correct path", "Application Not Found"); return; } m_Process = new Process { EnableRaisingEvents = true, StartInfo = { FileName = ApplicationName, Arguments = ApplicationParameters } }; //m_Process.Exited += new EventHandler(p_Exited); if (!string.IsNullOrEmpty(this.ApplicationWorkingDirectory) && Directory.Exists(this.ApplicationWorkingDirectory)) { m_Process.StartInfo.WorkingDirectory = this.ApplicationWorkingDirectory; } m_Process.Exited += delegate { m_CloseCallback(true); }; m_Process.Start(); // Wait for application to start and become idle m_Process.WaitForInputIdle(); m_AppWin = m_Process.MainWindowHandle; if (IntPtr.Zero == m_AppWin) { Log.WarnFormat("Unable to get handle for process on first try.{0}", LoopWaitForHandle ? " Polling 10 s for handle." : ""); if (LoopWaitForHandle) { DateTime startTime = DateTime.Now; while ((DateTime.Now - startTime).TotalSeconds < 10) { System.Threading.Thread.Sleep(50); // Refresh Process object's view of real process m_Process.Refresh(); m_AppWin = m_Process.MainWindowHandle; if (IntPtr.Zero != m_AppWin) { Log.Info("Successfully found handle via polling " + (DateTime.Now - startTime).TotalMilliseconds + " ms"); break; } } } } } catch (InvalidOperationException ex) { /* Possible Causes: * No file name was specified in the Process component's StartInfo. * -or- * The ProcessStartInfo.UseShellExecute member of the StartInfo property is true while ProcessStartInfo.RedirectStandardInput, * ProcessStartInfo.RedirectStandardOutput, or ProcessStartInfo.RedirectStandardError is true. */ MessageBox.Show(this, ex.Message, "Invalid Operation Error"); throw; } catch (Win32Exception ex) { /* * Checks are elsewhere to ensure these don't occur, but incase they do we're gonna bail with a nasty exception * which will hopefully send users kicking and screaming at me to fix this (And hopefully they will include a * stacktrace!) */ if (ex.NativeErrorCode == NativeMethods.ERROR_ACCESS_DENIED) { throw; } else if (ex.NativeErrorCode == NativeMethods.ERROR_FILE_NOT_FOUND) { throw; } } if (SuperPuTTY.PuTTYAppName + " Command Line Error" == this.m_Process.MainWindowTitle) { // dont' try to capture or manipulate the window Log.WarnFormat("Error while creating putty session: title={0}, handle={1}. Abort capture window", this.m_Process.MainWindowTitle, this.m_AppWin); MessageBox.Show("Could not start putty session: Arguments passed to commandline invalid.", "putty command line error."); this.m_AppWin = IntPtr.Zero; } if (this.m_AppWin != IntPtr.Zero) { // Set the application as a child of the parent form NativeMethods.SetParent(m_AppWin, this.Handle); // Show it! (must be done before we set the windows visibility parameters below NativeMethods.ShowWindow(m_AppWin, NativeMethods.WindowShowStyle.Maximize); // set window parameters (how it's displayed) long lStyle = NativeMethods.GetWindowLong(m_AppWin, NativeMethods.GWL_STYLE); lStyle &= ~(NativeMethods.WS_BORDER | NativeMethods.WS_THICKFRAME); NativeMethods.SetWindowLong(m_AppWin, NativeMethods.GWL_STYLE, lStyle); NativeMethods.WinEventDelegate lpfnWinEventProc = new NativeMethods.WinEventDelegate(WinEventProc); this.lpfnWinEventProcs.Add(lpfnWinEventProc); uint eventType = (uint)NativeMethods.WinEvents.EVENT_OBJECT_NAMECHANGE; this.m_hWinEventHooks.Add(NativeMethods.SetWinEventHook(eventType, eventType, IntPtr.Zero, lpfnWinEventProc, (uint)m_Process.Id, 0, NativeMethods.WINEVENT_OUTOFCONTEXT)); eventType = (uint)NativeMethods.WinEvents.EVENT_SYSTEM_FOREGROUND; this.m_hWinEventHooks.Add(NativeMethods.SetWinEventHook(eventType, eventType, IntPtr.Zero, lpfnWinEventProc, (uint)m_Process.Id, 0, NativeMethods.WINEVENT_OUTOFCONTEXT)); } else { MessageBox.Show("Process window not found.", "Process Window Not Found"); try { m_Process.Kill(); } catch (InvalidOperationException ex) { Log.WarnFormat("no process window found to kill: {0}", ex.Message); } return; } } if (this.Visible && this.m_Created && this.ExternalProcessCaptured) { // Move the child so it's located over the parent this.MoveWindow("OnVisChanged"); if (RefocusOnVisChanged && NativeMethods.GetForegroundWindow() != this.m_AppWin) { this.BeginInvoke(new MethodInvoker(delegate { this.ReFocusPuTTY("OnVisChanged"); })); } } base.OnVisibleChanged(e); }
public WindowLocationHook(IntPtr hwnd) { this.HWnd = hwnd; this.EventDelegate = new NativeMethods.WinEventDelegate(this.WinEventProc); }