/// <summary> /// 判断应用是否运行 /// </summary> /// <param name="processName">程序名称</param> /// <param name="exit"> 是否退出</param> /// <returns></returns> public static IDisposable Guard(out bool exit) { Process currentProcess = Process.GetCurrentProcess(); var processName = currentProcess.ProcessName; Mutex mutex = new Mutex(true, processName, out bool createNew); if (createNew) { exit = false; } else { Process[] processesByName = Process.GetProcessesByName(currentProcess.ProcessName); int num = 0; while (num < (int)processesByName.Length) { Process process = processesByName[num]; if (process.Id == currentProcess.Id || !(process.MainWindowHandle != IntPtr.Zero)) { num++; } else { WinApiHelper.SetForegroundWindow(process.MainWindowHandle); WinApiHelper.RestoreWindowAsync(process.MainWindowHandle); break; } } exit = true; } return(mutex); }
public static IEnumerable <KeyValuePair <Process, EnvDTE._DTE> > GetVSInstances() { IRunningObjectTable runningObjectTable = WinApiHelper.GetRunningObjectTable(); IEnumMoniker enumMoniker; runningObjectTable.EnumRunning(out enumMoniker); IMoniker[] monikers = new IMoniker[1]; for (enumMoniker.Reset(); enumMoniker.Next(1, monikers, IntPtr.Zero) == 0;) { EnvDTE._DTE dte; Process dteProcess; try { IBindCtx ctx = WinApiHelper.NewBindCtx(); string runningObjectName; monikers[0].GetDisplayName(ctx, null, out runningObjectName); if (!runningObjectName.StartsWith("!VisualStudio") && !runningObjectName.StartsWith("!WDExpress.DTE")) { continue; } object runningObjectVal; runningObjectTable.GetObject(monikers[0], out runningObjectVal); dte = runningObjectVal as EnvDTE._DTE; if (dte == null) { continue; } int dteProcessId = int.Parse(runningObjectName.Split(':')[1]); dteProcess = Process.GetProcessById(dteProcessId); } catch { continue; } yield return(new KeyValuePair <Process, EnvDTE._DTE>(dteProcess, dte)); } }
static void DoStart(string fileName, string workingDirectory, string argumentsString) { ProcessStartInfo psi = new ProcessStartInfo(fileName); psi.WorkingDirectory = workingDirectory ?? AppDomain.CurrentDomain.BaseDirectory; psi.Arguments = argumentsString; WinApiHelper.WaitForWindowAppears(Process.Start(psi)); }
protected override void OnInitialize() { (GetView() as WinMsgView).Owner = System.Windows.Application.Current.MainWindow; _keyBoardHookDelegate = new WinApiHelper.HookProc(KeyBoardHookProc); ProcessModule cModule = Process.GetCurrentProcess().MainModule; IntPtr hm = WinApiHelper.GetModuleHandle(cModule.ModuleName); hHook = WinApiHelper.SetWindowsHookEx(MSG_DEF.WH_KEYBOARD_LL, _keyBoardHookDelegate, hm, 0); }
private static IntPtr GetMinesweeperWindowPtr(IEnumerable <string> gameWindowNames) { foreach (var wndName in gameWindowNames) { var hWnd = WinApiHelper.FindWindow(null, wndName); if (hWnd != IntPtr.Zero) { return(hWnd); } } throw new WindowCannotBeFoundException(); }
/// <summary> Gets text from control by classname and its parent pointer using Win API methods </summary> /// <param name="hwndParent">Parent window (control) pointer</param> /// <param name="className">Class name of control</param> /// <param name="result">Variable for text store</param> /// <returns>Whether operation was successful</returns> public static bool GetDocumentTextBytes(IntPtr hwndParent, string className, out object result) { var childHandle = WinApiHelper.FindWindowEx(hwndParent, IntPtr.Zero, className, null); int subsize = WinApiHelper.SendMessage((int)childHandle, WinApiHelper.WM_GETTEXTLENGTH, 0, 0).ToInt32(); if (subsize > 0) { var subtitle = new StringBuilder(subsize + 1); WinApiHelper.SendMessage(childHandle, WinApiHelper.WM_GETTEXT, subtitle.Capacity, subtitle); result = subtitle.ToString(); return(true); } result = ""; return(false); }
private void CodeHelper_StartingExecution(object sender, EventArgs e) { new PermissionSet(PermissionState.Unrestricted).Assert(); // we start here monitoring thread _compilationCompleted.Set(); _threadsBefore = ThreadsInfo.Gather(); Debug.WriteLine("Initial thread info gathered"); _executingThreadID = WinApiHelper.GetCurrentThreadId(); _compileTime = DateTime.Now - _runAt; _memoryUsedAfterCompilation = AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize; PermissionSet.RevertAssert(); }
private void Window_SourceInitialized(object sender, EventArgs e) { // Disable maximize functionality through the WinAPI call var hwnd = new WindowInteropHelper((Window)sender).Handle; WinApiHelper.DisableMaximizeFunctionality(hwnd); // Create WPF-styled wndProc function to receive PInvoke calls var source = PresentationSource.FromVisual(this) as System.Windows.Interop.HwndSource; if (source != null) { source.AddHook(wndProc); } }
/// <summary> /// 发送消息 /// </summary> /// <param name="message"></param> public static void Stop() { var processes = Process.GetProcessesByName("ffmpeg"); if (processes != null) { foreach (var p in processes) { WinApiHelper.AttachConsole(p.Id); // WinApiHelper.SetConsoleCtrlHandler(IntPtr.Zero, true); WinApiHelper.GenerateConsoleCtrlEvent(0, p.Id); WinApiHelper.FreeConsole(); break; } } }
public void UpdateCellStates(IEnumerable <Cell> cells) { _colorsCache = new Dictionary <int, Color>(); var hdc = IntPtr.Zero; try { hdc = WinApiHelper.GetDC(_minesweeperWindow); cells.ForEach(x => UpdateCellState(x, hdc)); } finally { if (hdc != IntPtr.Zero) { WinApiHelper.ReleaseDC(_minesweeperWindow, hdc); } } }
static void T2() { while (true) { IntPtr mwh = WinApiHelper.FindWindow(null, "向日葵远程控制"); //主窗口句柄 WinApiHelper.SetActiveWindow(mwh); WinApiHelper.ShowWindow(mwh, WindowState.SW_RESTORE); WinApiHelper.Click(mwh, 328, 335); Thread.Sleep(500); Bitmap data = WinApiHelper.CutControlBitmap(mwh); data.Save(DateTime.Now.ToFileTime() + ".png"); WinApiHelper.Click(mwh, 310, 335); Thread.Sleep(500); WinApiHelper.ShowWindow(mwh, WindowState.SW_MINIMIZE); WinApiHelper.Click(mwh, 1, 1); Thread.Sleep(1000 * 5); } }
public void SendMsg(string windowName) { IntPtr hWnd = WinApiHelper.FindWindow(null, windowName); if (hWnd == IntPtr.Zero) { return; } // WinApiHelper.SetWindowText(hWnd, "Hello"); // WinApiHelper.ShowWindow(hWnd, 5); // WinApiHelper.SetForegroundWindow(hWnd); // WinApiHelper.SendMessage(hWnd, 0x1081, 0, "msg"); LONGDATASTRUCT longData = new LONGDATASTRUCT() { sender = System.Windows.Application.Current.MainWindow.Title, content = "你好。", tag = "来自 C# WPF" }; // 将数据拷贝至非托管内存 IntPtr longDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(longData)); Marshal.StructureToPtr <LONGDATASTRUCT>(longData, longDataPtr, true); COPYDATASTRUCT copyData = new COPYDATASTRUCT() { dwData = IntPtr.Zero, cbData = Marshal.SizeOf(longData), lpData = longDataPtr, }; IntPtr cpDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(copyData)); Marshal.StructureToPtr(copyData, cpDataPtr, true); WinApiHelper.SendMessage(hWnd, MSG_DEF.WM_COPYDATA, IntPtr.Zero, cpDataPtr); // 释放掉相应的非托管内存数据 Marshal.FreeHGlobal(longDataPtr); Marshal.FreeHGlobal(cpDataPtr); }
private void UpdateCellState(Cell cell, IntPtr hdc) { foreach (var kvp in CellStateDeterminationList) { Color color; var cacheKey = kvp.Key.XPointGetter(cell.Col) * 100 + kvp.Key.YPointGetter(cell.Row); if (!_colorsCache.TryGetValue(cacheKey, out color)) { color = WinApiHelper.GetColor(hdc, kvp.Key.XPointGetter(cell.Col), kvp.Key.YPointGetter(cell.Row)); _colorsCache[cacheKey] = color; } if (color != kvp.Key.Color) { continue; } cell.UpdateState(kvp.Value); break; } }
private static void YjkProcessTest() { string file = @"E:\360data\重要数据\桌面\幼儿园(1)\幼儿园\幼儿园.yjk"; try { //Process process = new Process(); //Process.Start(file, "yjk_exportydbdefault"); //while (true) { // Thread.Sleep(1000); // Process[] processArray = Process.GetProcessesByName("yjks"); // if (processArray.Length > 0) { // break; // } //} string fileExtent = string.Format(".{0}", Path.GetExtension(file)); IntPtr windowPtr = WinApiHelper.FindWindowHandle("盈建科软件"); IntPtr btnSetPtr = WinApiHelper.GetControlInptr(windowPtr, "Settings..."); Console.ReadLine(); } catch (Exception ex) { throw ex; } }
private int KeyBoardHookProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode < 0) { return(-1); } KeyBoardHookStruct keyDataFromHook = Marshal.PtrToStructure <KeyBoardHookStruct>(lParam); int keyData = keyDataFromHook.vkCode; if (wParam.ToInt32() == MSG_DEF.WM_KETDOWN || wParam.ToInt32() == MSG_DEF.WN_SYSKEYDOWN) { Key key = KeyInterop.KeyFromVirtualKey(keyData); } if (wParam.ToInt32() == MSG_DEF.WM_KEYUP || wParam.ToInt32() == MSG_DEF.WN_SYSKEYDOWN) { // } return(WinApiHelper.CallNextHookEx(hHook, nCode, wParam, lParam)); }
public static IDisposable SingleInstanceApplicationGuard(string applicationName, out bool exit) { Mutex mutex = new Mutex(true, applicationName + AssemblyInfo.VersionShort); if (mutex.WaitOne(0, false)) { exit = false; } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id && process.MainWindowHandle != IntPtr.Zero) { WinApiHelper.SetForegroundWindow(process.MainWindowHandle); WinApiHelper.RestoreWindowAsync(process.MainWindowHandle); break; } } exit = true; } return(mutex); }
public static bool RestoreWindowAsync(IntPtr hwnd) { return(WinApiHelper.Import.ShowWindowAsync(hwnd, (WinApiHelper.IsMaxmimized(hwnd) ? 3 : 9))); }
/* C++ 中相关代码 * 处理 WM_COPYDATA 消息 * Header File(.h) * --------------------------------------------------------------------- * ... * afx_msg BOOL OnCopyData(CWnd *pWnd, COPYDATASTRUCT *pCopyDataStruct); * ... * DECLARE_MESSAGE_MAP() * --------------------------------------------------------------------- * * Source File(.cpp) * BEGIN_MESSAGE_MAP(CxxxDlg, CDialogEx) * ... * ON_WM_COPYDATA() * ... * END_MESSAGE_MAP() * ... * ... * ... * BOOL CxxxDlg::OnCopyData(CWnd *pWnd, COPYDATASTRUCT *pCopyDataStruct) * { * if (pCopyDataStruct != NULL) * { * PMYDATASTRUCT data = (PMYDATASTRUCT)(pCopyDataStruct->lpData); * DWORD dwLen = pCopyDataStruct->cbData; * char buffer[512] = { 0 }; * memcpy(buffer, data->content, 512); * // TODO: 数据处理 * TRACE(buffer); * } * * return CDialogEx::OnCopyData(pWnd, pCopyDataStruct); * } */ public void Cleanup() { // TODO: Cleanup WinApiHelper.UnhookWindowsHookEx(hHook); }
public void NewGame() { WinApiHelper.PostMessage(_minesweeperWindow, WindowMessages.WM_KEYDOWN, (IntPtr)Keys.F2, IntPtr.Zero); }
public void TickMine(int row, int col) { WinApiHelper.MouseClick(_minesweeperWindow, MouseButton.Right, Coords.ColToCoord(col), Coords.RowToCoord(row)); }
public void OpenCell(int row, int col) { WinApiHelper.MouseClick(_minesweeperWindow, MouseButton.Left, Coords.ColToCoord(col), Coords.RowToCoord(row)); }
private void Application_Startup(object sender, StartupEventArgs e) { //create the notifyicon (it's a resource declared in NotifyIconResources.xaml NotifyIcon = (TaskbarIcon)FindResource("NotifyIcon"); Screener screener = new Screener(); //to make screen List <ShortcutModel> Shurtcuts = new List <ShortcutModel> { new ShortcutModel() { Name = "Kombajn do pracy", Describes = "Skrótowe wejście w potrzebne foldery", AllModifs = false, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.None, KeyCode = "1", actionOnClick = () => { string kombajnDoPracyPath = @"C:\Users\dante\source\Repos 2020\KombajnyDeluxe\KombajnyDeluxe\bin\Release\KombajnDoPracy.exe"; Process.Start(kombajnDoPracyPath); } }, new ShortcutModel() { Name = "Screener", Describes = "Robi screena aktualnego monitora i wrzuca go do folderu zbiorczego z innymi screenami", AllModifs = false, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.None, KeyCode = "2", actionOnClick = () => { try { string screenPath = screener.TakeScreenshot(); var screenAnimation = new ScreenAnimationWindow(screenPath); screenAnimation.Left = SystemParameters.VirtualScreenWidth - 250; screenAnimation.Top = 0; screenAnimation.Show(); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Exception", MessageBoxButton.OK, MessageBoxImage.Warning); LogError(ex.ToString()); } } }, new ShortcutModel() { Describes = "Wycina określony obszar", AllModifs = false, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.None, KeyCode = "E", actionOnClick = () => { string snippingToolProcess = string.Empty; if (!Environment.Is64BitProcess) { snippingToolProcess = @"C:\Windows\sysnative\SnippingTool.exe"; } else { snippingToolProcess = @"C:\WINDOWS\system32\SnippingTool.exe"; } Process process = new Process(); process.StartInfo.FileName = snippingToolProcess; process.Start(); IntPtr handle = process.Handle; WinApiHelper.SetForegroundWindow(handle); } }, new ShortcutModel() { Name = "Linijka", Describes = "Miarka pikselów na ekranie", AllModifs = false, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.None, KeyCode = "L", actionOnClick = () => { string rulerProcessPath = @"C:\Users\dante\source\Repos 2020\Linijka\MojaLinijka\bin\Debug\Linijka.exe"; Process process = new Process(); process.StartInfo.FileName = rulerProcessPath; process.Start(); IntPtr handle = process.Handle; WinApiHelper.SetForegroundWindow(handle); } }, new ShortcutModel() { Name = "Color Picker", Describes = "Pokazuje kolor z hexa", AllModifs = false, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.None, KeyCode = "T", actionOnClick = () => { string snippingCzasowyWylacznik = @"C:\Users\dante\source\Repos 2020\GetColor\GetColor\bin\Debug\GetColor.exe"; Process.Start(snippingCzasowyWylacznik); } }, new ShortcutModel() { Name = "Open Daily text file", Describes = "Otwiera plik tekstowy z folderu Notatki na dany dzień", AllModifs = false, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.None, KeyCode = "3", actionOnClick = () => { string dailyTextFile = ButtonPathGenerator.GetDailyFileFullPath(".txt"); Process process = new Process(); process.StartInfo.FileName = dailyTextFile; process.Start(); IntPtr handle = process.Handle; WinApiHelper.SetForegroundWindow(handle); } }, new ShortcutModel() { Name = "Open All Dane -> Wazne Notsy", Describes = "Otwiera plik tekstowy z waznym tekstem", AllModifs = false, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.None, KeyCode = "4", actionOnClick = () => { string dailyTextFile = ButtonPathGenerator.GetAllDataNoteFullPath(); Process process = new Process(); process.StartInfo.FileName = dailyTextFile; process.Start(); IntPtr handle = process.Handle; WinApiHelper.SetForegroundWindow(handle); } }, new ShortcutModel() { Name = "DisplayScreens from today", Describes = "Wszystkie screeny z dzisiaj", AllModifs = false, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.None, KeyCode = "5", actionOnClick = () => { string path = @"C:\Users\dante\source\Repos 2020\KombajnyDeluxe\DisplayScreens\bin\Release\netcoreapp3.1\DisplayScreens.exe"; string searchScreenFrom = @"C:\Users\dante\OneDrive\Pulpit\MojeDane"; int dateRange = 24; Process process = new Process(); process.StartInfo.FileName = path; process.StartInfo.Arguments = $"{dateRange} \"{searchScreenFrom}\""; process.Start(); IntPtr handle = process.Handle; WinApiHelper.SetForegroundWindow(handle); } }, new ShortcutModel() { Name = "DisplayScreens from weeek", Describes = "Wszystkie screeny z tygodnia", AllModifs = false, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.None, KeyCode = "6", actionOnClick = () => { string path = @"C:\Users\dante\source\Repos 2020\KombajnyDeluxe\DisplayScreens\bin\Release\netcoreapp3.1\DisplayScreens.exe"; string searchScreenFrom = @"C:\Users\dante\OneDrive\Pulpit\MojeDane"; int dateRange = 1; Process process = new Process(); process.StartInfo.FileName = path; process.StartInfo.Arguments = $"{dateRange} \"{searchScreenFrom}\""; process.Start(); IntPtr handle = process.Handle; WinApiHelper.SetForegroundWindow(handle); } }, new ShortcutModel() { Name = "Process Killer", Describes = "Zabija proces po nazwie", AllModifs = true, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.Alt, KeyCode = "R", actionOnClick = () => { string processKiller = @"C:\Users\dante\source\Repos 2020\Process Killer\Process Killer\bin\Debug\Process Killer.exe"; Process.Start(processKiller); } }, new ShortcutModel() { Name = "Quit PC", Describes = "Wyłącza PC", AllModifs = true, SelectedModificator = ModificatorNumeration.Ctrl, AlternateSelectedModificator = ModificatorNumeration.Alt, KeyCode = "Q", actionOnClick = () => { //MessageBox.Show("shutdown"); Process.Start("shutdown", "/s /t 0"); } } }; //Set global hook GlobalHook = new GlobalHookBase(Shurtcuts); //assign list to notifyIcon if (NotifyIcon != null) { NotifyIcon.DataContext = new NotifyIconViewModel(Shurtcuts); } }
protected override void OnStartup(StartupEventArgs e) { if (!_mutex.WaitOne(TimeSpan.Zero, true)) { var pr = Process.GetProcessesByName(Constants.ProgramName); if (pr.Length > 1) { foreach (Process process in pr) { foreach (ProcessThread threadInfo in process.Threads) { IntPtr[] windows = GetWindowHandlesForThread(threadInfo.Id); if (windows != null && windows.Length > 0) { foreach (IntPtr hWnd in windows) { WinApiHelper.SendMessageToShowMainWindow(hWnd); } } } } } else // if somebody renamed our .exe file { MessageBox.Show("Another instance of the application is already running.", Constants.ProgramName, MessageBoxButton.OK, MessageBoxImage.Information); } Current.Shutdown(); return; } base.OnStartup(e); DataManager.ThisProcessId = Process.GetCurrentProcess().Id; DataManager.OpenConfiguration(); DataManager.OpenIgnoredWordsFile(); MainWindow = new MainWindow(); MainWindow.Closing += (sender, args) => { if (!_isExit) { args.Cancel = true; MainWindow.Hide(); _listWindowIsShown = false; } else { DataManager.Configuration.WinPositionX = MainWindow.Left; DataManager.Configuration.WinPositionY = MainWindow.Top; DataManager.Configuration.WinSizeHeight = MainWindow.Height; DataManager.Configuration.WinSizeWidth = MainWindow.Width; DataManager.SaveConfiguration(); } }; MainWindow.Closed += (sender, args) => { foreach (Window win in Current.Windows) { win.Close(); } }; ((MainWindow)MainWindow).OnWindowShowing += () => { _listWindowIsShown = true; }; _notifyIcon = new System.Windows.Forms.NotifyIcon { Icon = AngryShop.Properties.Resources.STE_White_MultiImage, Visible = true, Text = Constants.ProgramName }; _notifyIcon.MouseClick += (s, args) => { if (args.Button == MouseButtons.Left) { ((MainWindow)MainWindow).ShowWindow(); } }; var menuItemConfig = new System.Windows.Forms.MenuItem("Configuration...") { DefaultItem = true }; menuItemConfig.Click += menuItemConfigurationOnClick; var menuItemExit = new System.Windows.Forms.MenuItem("Exit Application"); menuItemExit.Click += (s, args) => exitApplication(); _notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(new[] { menuItemConfig, new System.Windows.Forms.MenuItem("-"), menuItemExit }); setWindowVisibilityBehaviour(); ((MainWindow)MainWindow).ShowWindow(); _mutex.ReleaseMutex(); }