protected override void ExecuteInternal(CheckPixelDifferenceParameter param, CancellationToken token) { var stopWatch = new Stopwatch(); while (true) { token.ThrowIfCancellationRequested(); stopWatch.Restart(); var color = Win32ApiHelper.GetPixelColorFromDesktop(param.Pixel.X, param.Pixel.Y); stopWatch.Stop(); // For some reason, the GetPixel method of the WinAPI is executed every time with different duration (from 15 to 35 ms). // The rest of code HAS TO be executed every time after the same duration, so we'll wait up to 100ms Thread.Sleep(100 - (int)stopWatch.ElapsedMilliseconds); if (!(color.R == param.HookedColor.R && color.G == param.HookedColor.G && color.B == param.HookedColor.B)) { continue; } _messageBus.Publish(new PixelColorChangedMessage(this)); break; } }
protected override void ExecuteInternal(SendKeyEventParameter param, CancellationToken token) { Logger.Information("Sending KeyPressedEvent with {@sendKeyEventParameter}", param); Thread.Sleep(param.DelayDuration); Win32ApiHelper.SendKeyPressedEvent(param.HookedKey); }
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e) { foreach (var Path in SelectedPathArray) { Win32ApiHelper.ShellExecute(IntPtr.Zero, "", Path, "", "", Win32ApiHelper.ShowCommands.SW_SHOWNORMAL); } }
public override void Text(IShipmentAutomationControl control, string text) { if (control.IsTypedInputRequired) { TypeTextWithFocus(control, text); Keyboard.Type(Key.Enter); return; } if (control.IsCharInputRequired) { control.AutomationElement.SetFocus(); Thread.Sleep(1000); Keyboard.Type(Key.Back); Win32ApiHelper.SendChars(control.NativeHwnd, text, 70); Keyboard.Type(Key.Enter); return; } Win32ApiHelper.SendMessage(control.NativeHwnd, Win32ApiHelper.WM_SETTEXT, 0, text); if (control.IsFocusedInputRequired) { control.AutomationElement.SetFocus(); Keyboard.Type(Key.Enter); } }
public override void Selection(IShipmentAutomationControl control, string text) { if (Selection(control) == text) { return; } if (control.IsCharInputRequired) { Win32ApiHelper.SendMessage(control.NativeHwnd, 335, 1, null); Win32ApiHelper.SendMessage(control.NativeHwnd, Win32ApiHelper.CB_SELECTSTRING, Win32ApiHelper.SEARCH_ALL, text); Win32ApiHelper.SendChars(control.NativeHwnd, text, 10); Win32ApiHelper.SendMessage(control.NativeHwnd, 335, 0, null); return; } var contents = GetListBoxContents(control.NativeHwnd); var item = contents.FirstOrDefault(c => string.Equals(c, text, StringComparison.CurrentCultureIgnoreCase)); var index = contents.IndexOf(item); if (item != null && index > -1) { Win32ApiHelper.SendMessage(control.NativeHwnd, Win32ApiHelper.CB_SETCURSEL, index, null); } else { Text(control, text); } }
/// <summary> /// 获取更高级别的操作系统权限。 /// </summary> /// <param name="privilege">需要获得的权限。</param> /// <exception cref="Win32ApiErrorInformationException">当出现未知的或者无法处理的Win32Api错误代码时,则需要抛出这个异常。</exception> public static void GetSystemAuthority(string privilege) { if (!Win32ApiHelper.CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges")) { return; } IntPtr tokenHandle = IntPtr.Zero; SLocallyUniqueIdentifier luid = new SLocallyUniqueIdentifier(); STokenPrivileges newPrivileges = new STokenPrivileges(); STokenPrivileges tokenPrivileges; if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle)) { throw new Win32ApiErrorInformationException(); } if (LookupPrivilegeValue(null, privilege, ref luid) == 0) { throw new Win32ApiErrorInformationException(); } tokenPrivileges.PrivilegeCount = 1; tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED; tokenPrivileges.Privileges.ParticularLuid = luid; int size = 4; if (AdjustTokenPrivileges(tokenHandle, 0, ref tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), ref newPrivileges, ref size) == 0) { throw new Win32ApiErrorInformationException(); } }
/// <summary> /// Обработчик события перемещения окна /// </summary> private void HeaderPanel_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Win32ApiHelper.ReleaseCapture(); Win32ApiHelper.SendMessage(Handle, Win32ApiHelper.WM_NCLBUTTONDOWN, Win32ApiHelper.HT_CAPTION, 0); } }
public override void Click(IShipmentAutomationButton control) { var button = (ShipmentAutomationBase)control; if (button != null) { Win32ApiHelper.SendMessage(button.NativeHwnd, Win32ApiHelper.BM_CLICK, 0, IntPtr.Zero); } }
public override bool Checked(IShipmentAutomationControl control) { try { var state = Win32ApiHelper.SendMessage(control.NativeHwnd, Win32ApiHelper.BM_GETCHECK, 0, IntPtr.Zero); return(state == new IntPtr(Win32ApiHelper.BST_CHECKED)); } catch (Exception) { return(false); } }
private List <string> GetListBoxContents(IntPtr listBoxHwnd) { var cnt = (int)Win32ApiHelper.SendMessage(listBoxHwnd, Win32ApiHelper.CB_GETCOUNT, IntPtr.Zero, null); var listBoxContent = new List <string>(); for (var i = 0; i < cnt; i++) { var sb = new StringBuilder(256); Win32ApiHelper.SendMessage(listBoxHwnd, Win32ApiHelper.CB_GETLBTEXT, (IntPtr)i, sb); listBoxContent.Add(sb.ToString()); } return(listBoxContent); }
protected Process RunApplication(string processName) { //Validate if (string.IsNullOrEmpty(processName)) { throw new Exception(InformationResources.ERROR_EXTERNAL_APPLICATION_PROCESS_NAME_EMPTY); } //Get application process identificator var process = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains(processName)); //Set Window on Top Win32ApiHelper.SetWindowTopMost(process); return(process); }
public override void Checked(IShipmentAutomationControl control, bool value) { if (control.IsTypedInputRequired) { var current = Checked(control); if (current != value) { control.AutomationElement.SetFocus(); Keyboard.Type(Key.Space); } return; } var bsd = value ? Win32ApiHelper.BST_CHECKED : Win32ApiHelper.BST_UNCHECKED; Win32ApiHelper.SendMessage(control.NativeHwnd, Win32ApiHelper.BM_SETCHECK, bsd, IntPtr.Zero); }
public override string Text(IShipmentAutomationControl control) { try { var length = Win32ApiHelper.SendMessage(control.NativeHwnd, Win32ApiHelper.WM_GETTEXTLENGTH, 0, 0); if (length > 0) { var text = new StringBuilder(length + 1); Win32ApiHelper.SendMessage(control.NativeHwnd, Win32ApiHelper.WM_GETTEXT, text.Capacity, text); return(text.ToString()); } return(null); } catch (Exception) { return(null); } }
protected override void WndProc(ref Message m) { if (m.Msg == winuser_h.WM_SYSCOMMAND && notifyWindow != null) { if (m.WParam.ToInt32() == winuser_h.SC_MINIMIZE) { notifyWindow.Owner = null; this.InvokeIfRequired(() => Win32ApiHelper.ShowWindow(Handle, winuser_h.SW_HIDE)); ShowInTaskbar = false; } if (m.WParam.ToInt32() == winuser_h.SC_RESTORE) { notifyWindow.Owner = null; notifyWindow.WindowState = FormWindowState.Normal; } } base.WndProc(ref m); }
public override string Selection(IShipmentAutomationControl control) { try { var index = Win32ApiHelper.SendRefMessage(control.NativeHwnd, Win32ApiHelper.CB_GETCURSEL, 0, null).ToInt32(); if (index > 1) { var ssb = new StringBuilder(256, 256); Win32ApiHelper.SendRefMessage(control.NativeHwnd, Win32ApiHelper.CB_GETLBTEXT, index, ssb); return(ssb.ToString()); } return(Text(control)); } catch (Exception) { return(string.Empty); } }
/// <summary> /// Выполняет выход из сеанса пользователя, зевершение работы системы или её перезагрузку /// </summary> /// <param name="procHandle">Дескриптор приложения выполняющего вызов данного метода</param> /// <param name="shutdownFlag">Вариант завершения работы</param> public static void ExitWindows(IntPtr procHandle, uint shutdownFlag) { IntPtr tokenHandle = IntPtr.Zero; try { if (!Win32ApiHelper.OpenProcessToken(procHandle, TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, out tokenHandle)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Не удалось открыть дескриптор токена процесса"); } Win32ApiHelper.TOKEN_PRIVILEGES tokenPrivs = new Win32ApiHelper.TOKEN_PRIVILEGES(); tokenPrivs.PrivilegeCount = 1; tokenPrivs.Privileges = new Win32ApiHelper.LUID_AND_ATTRIBUTES[1]; tokenPrivs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (!Win32ApiHelper.LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, out tokenPrivs.Privileges[0].Luid)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Не удалось преобразовать имя привилегии выключения"); } if (!Win32ApiHelper.AdjustTokenPrivileges(tokenHandle, false, ref tokenPrivs, 0, IntPtr.Zero, IntPtr.Zero)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Не удалось настроить права токена процесса"); } if (!Win32ApiHelper.ExitWindowsEx(shutdownFlag, (uint)Win32ApiHelper.ShutdownReasonCodes.SHTDN_REASON_MAJOR_APPLICATION | (uint)Win32ApiHelper.ShutdownReasonCodes.SHTDN_REASON_MINOR_INSTALLATION | (uint)Win32ApiHelper.ShutdownReasonCodes.SHTDN_REASON_FLAG_PLANNED)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Ошибка при выключении системы"); } } finally { if (tokenHandle != IntPtr.Zero) { Win32ApiHelper.CloseHandle(tokenHandle); } } }
public void ReloadActiveBrowserPage(string shipmentId) { var topMostBrowser = GetOrderedBrowserProcesses().FirstOrDefault(); if (topMostBrowser != null) { try { var shipmentUriData = GetShipmentUriData(); if (!shipmentUriData.IsDataCorrect() || shipmentUriData.ShipmentNbr != shipmentId) { return; } Win32ApiHelper.SetWindowTopMost(topMostBrowser); _automationUtils.RefreshBrowserCurrentPage(); } catch (NetworkActiveUriNotFoundException) { //Just do nothing, not reload browser } } }
private void lvBrowser_MouseDoubleClick(object sender, MouseEventArgs e) { if (lvBrowser.SelectedItems.Count == 0) { return; } var newLvi = lvBrowser.SelectedItems[0]; var Path = newLvi.Name; if (Directory.Exists(Path)) { ListFolder(Path); } else if (File.Exists(Path)) { Win32ApiHelper.ShellExecute(IntPtr.Zero, "", Path, "", "", Win32ApiHelper.ShowCommands.SW_SHOWNORMAL); } else { MessageBox.Show("路径无效"); } }
private void ReadConfiguration() { AvailableKeys = Enum.GetNames(typeof(Keys)).ToList(); // to setup a key for the keyboard hook HookedKey = _appConfigProvider.GetConfig().HookedKeyCode; // initial setup of preview window _previewUpdateTask.Execute((() => new Point(CoordinateX, CoordinateY), DisableHookCommand.CanExecute), CancellationToken.None); _screenResolution = Win32ApiHelper.GetScreenResolution(); try { _hookedColor = ColorHelper.FromRgb(_appConfigProvider.GetConfig().HookedRgbColorCode); } catch (Exception e) { _hookedColor = Constants.GtaButtonColor; Logger.Error(e, "Couldn't parse rgb code"); } }
/// <summary> /// 重新启动Windows。 /// </summary> /// <returns>如果操作成功,则返回ERROR_SUCCESS(API定义:#define ERROR_SUCCESS 0L),否则将会显示其他的错误代码。</returns> public static long ResetBoot() { GetSystemAuthority(SE_SHUTDOWN_NAME); ExitWindowsEx(EWX_REBOOT, 0); return(Win32ApiHelper.GetLastWin32ApiError()); }
static void Main(string[] args) { Console.WriteLine("关闭【计算器】出口"); Win32ApiHelper.CloseWindow("计时器"); Console.ReadKey(); }
/// <summary> /// 关闭Windows。 /// </summary> /// <returns>如果操作成功,则返回ERROR_SUCCESS(WIN32_API定义:#define ERROR_SUCCESS 0L),否则将会显示其他的错误代码。</returns> public static long Shutdown() { GetSystemAuthority(SE_SHUTDOWN_NAME); ExitWindowsEx(EWX_SHUTDOWN, 0); return(Win32ApiHelper.GetLastWin32ApiError()); }
public Win32ApiErrorInformationException() : base(Win32ApiHelper.FormatErrorCode(Marshal.GetLastWin32Error())) { }
public void CreateProcessTest() { var path = @"C:\Windows\System32\notepad.exe"; Win32ApiHelper.CreateProcess(path); }
/// <summary> /// 强制中断当前用户的所有进程,即强制注销。 /// </summary> /// <returns>如果操作成功,则返回ERROR_SUCCESS(API定义:#define ERROR_SUCCESS 0L),否则将会显示其他的错误代码。</returns> public static long InterruptAllUserProcess() { GetSystemAuthority(SE_SHUTDOWN_NAME); ExitWindowsEx(EWX_FORCE, 0); return(Win32ApiHelper.GetLastWin32ApiError()); }
/// <summary> /// 注销当前用户,但是不退出Windows。 /// </summary> /// <returns>如果操作成功,则返回ERROR_SUCCESS(API定义:#define ERROR_SUCCESS 0L),否则将会显示其他的错误代码。</returns> public static long LogOff() { GetSystemAuthority(SE_SHUTDOWN_NAME); ExitWindowsEx(EWX_LOGOFF, 0); return(Win32ApiHelper.GetLastWin32ApiError()); }
public void GetWindowStationNamesTest() { var actual = Win32ApiHelper.GetWindowStationNames()?.Any() ?? false; Assert.IsTrue(actual); }