OpenHelp() { if (m_oHelpProcess != null) { // The help window is already open. Activate it. Win32Functions.SetForegroundWindow( m_oHelpProcess.MainWindowHandle); return; } // It's assumed that the build process placed a copy of the help file // in the application folder. m_oHelpProcess = Process.Start(Path.Combine( GetApplicationFolder(), HelpFileName)); m_oHelpProcess.EnableRaisingEvents = true; m_oHelpProcess.Exited += (Object, EventArgs) => { m_oHelpProcess.Dispose(); m_oHelpProcess = null; }; }
private void MenuItemShowPropertiesDialogClick(object sender, RoutedEventArgs e) { if (lstBox.SelectedIndex != -1) { try { var item = lstBox.SelectedItem as TaskItemQuick; if (item != null) { string pAddress = iphelper.Helper.GetProcessFullPath(item.ProcessId); Win32Functions.ShowFileProperties(pAddress); } } catch (Exception exp) { MessageBox.Show( "Unable to show Properties dialog due the following reason :" + Environment.NewLine + String.Format("Error Source : {0}, Error Message :{1}, Target Site Name:{2}", exp.Source, exp.Message , exp.TargetSite.Name) , "Operation Exception", MessageBoxButton.OK, MessageBoxImage.Stop); Trace.WriteLine("Something Went Wrong! :" + exp.Message); } } }
public static void SendDpiChangedMessage(IntPtr windowHandle, int dpi) { if (Win32Functions.GetWindowRect(windowHandle, out RECT rect)) { var res = Win32Functions.SendMessage(windowHandle, Win32Functions.WM_DPICHANGED, new IntPtr(dpi | (dpi << 16)), rect); } }
public static void BringToFront(this Window window) { // Bring window to front without activating it // https://stackoverflow.com/a/14211193/942659 Win32Functions.SetWindowPos((new WindowInteropHelper(window)).Handle, Win32Functions.HWND_TOP, 0, 0, 0, 0, SetWindowPosFlags.IgnoreMove | SetWindowPosFlags.IgnoreResize | SetWindowPosFlags.DoNotActivate); }
private void CloseWindowProcess(IntPtr windowHandle) { var myProcId = Process.GetCurrentProcess().Id; Win32Functions.GetWindowThreadProcessId(windowHandle, out uint consoleRootProcessId); // https://stackoverflow.com/a/28616832/942659 // TODO: Create console event handler for reliability Win32Functions.AttachConsole(consoleRootProcessId); uint[] procIds = new uint[1024]; Win32Functions.GetConsoleProcessList(procIds, 1024); Win32Functions.FreeConsole(); foreach (var procId in procIds) { if (procId == 0) { continue; } if (procId == myProcId) { continue; } try { var process = Process.GetProcessById((int)procId); process.Kill(); } catch { } } }
public void Dispose() { UnLock().Wait(); Win32Functions.CloseHandle(_driveHandle); _driveHandle = IntPtr.Zero; _driveName = null; GC.SuppressFinalize(this); }
private void HookForegroundWindowEvent() { windowForegroundHookCallback = new Win32Functions.WinEventDelegate(ForegroundWinEventProc); var hook = Win32Functions.SetWinEventHook(Win32Functions.EVENT_SYSTEM_FOREGROUND, Win32Functions.EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, windowForegroundHookCallback, 0, 0, Win32Functions.WINEVENT_OUTOFCONTEXT); }
public async Task <bool> Eject() { return(await Task.Run(() => { uint Dummy = 0; return Win32Functions.DeviceIoControl(_driveHandle, Win32Functions.IOCTL_STORAGE_EJECT_MEDIA, IntPtr.Zero, 0, IntPtr.Zero, 0, ref Dummy, IntPtr.Zero) != 0; })); }
private void HookCreateDestroyWindowEvent() { windowCreateDestroyHookCallback = new Win32Functions.WinEventDelegate(CreateDestroyWinEventProc); var hook = Win32Functions.SetWinEventHook(Win32Functions.EVENT_OBJECT_CREATE, Win32Functions.EVENT_OBJECT_DESTROY, IntPtr.Zero, windowCreateDestroyHookCallback, 0, 0, Win32Functions.WINEVENT_OUTOFCONTEXT); }
private void CalculateSpeed() { long sentBytes = 0; long recivedBytes = 0; foreach (NetworkInterface nic in _operationalNiCs) { IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics(); sentBytes += interfaceStats.BytesSent; recivedBytes += interfaceStats.BytesReceived; } long sentSpeed = sentBytes - _totalSentbytes; long recivedSpeed = recivedBytes - _totalReceivedbytes; if (_totalSentbytes == 0 && _totalReceivedbytes == 0) { sentSpeed = 0; recivedSpeed = 0; } GlobalReceives += recivedSpeed; GlobalSent += sentSpeed; lbl_Download.Content = Helper.UsageStringHelper(recivedSpeed, NetworkSettings.UnitTypes.KBytepers); lbl_Upload.Content = Helper.UsageStringHelper(sentSpeed, NetworkSettings.UnitTypes.KBytepers); _networkUsage.Add(new NetworkUsageData(DateTime.Now, sentSpeed, recivedSpeed)); lbl_MaxMarker.Content = Helper.UsageStringHelper(Mathematics.GetUpperRounded(_networkUsage.GetMaximumAtAll()), NetworkSettings.UnitTypes.KBytepers); if (MainWindow.Instance != null) { MainWindow.Instance.TooltipTextBlock.Text = String.Format("Download : {0} , Uploads : {1}", lbl_Download.Content, lbl_Upload.Content); Icon icofile = _networkUsage.GenerateIconFromCollection(); if (icofile != null) { MainWindow.Instance.taskbarIcon.Icon = icofile; if (_networkUsage.PrevPointer != IntPtr.Zero) { Win32Functions.DestroyIcon(_networkUsage.PrevPointer); } icofile.Dispose(); } } _totalSentbytes = sentBytes; _totalReceivedbytes = recivedBytes; if (DetailedViewModel.Instance != null) { DetailedViewModel.Instance.RefreshLables(GlobalReceives, GlobalSent); } }
public async Task <bool> IsCdInDrive() { return(await Task.Run(() => { uint dummy = 0; var check = Win32Functions.DeviceIoControl(_driveHandle, Win32Functions.IOCTL_STORAGE_CHECK_VERIFY, IntPtr.Zero, 0, IntPtr.Zero, 0, ref dummy, IntPtr.Zero); return check != 0; })); }
private CdDrive(string driveName) { if (Win32Functions.GetDriveType(driveName + ":\\") != Win32Functions.DriveTypes.DRIVE_CDROM) { throw new InvalidOperationException("Drive '" + driveName + "' is not an optical disc drive."); } _driveName = driveName; _driveHandle = CreateDriveHandle().Result; }
private void Window_SourceInitialized(object sender, EventArgs e) { this.EnableAcrylicBlur(); if (initialAbsolutePosition.HasValue) { var interop = new WindowInteropHelper(this); Win32Functions.SetWindowPos(interop.Handle, IntPtr.Zero, (int)initialAbsolutePosition.Value.X, (int)initialAbsolutePosition.Value.Y, 0, 0, Win32.Enums.SetWindowPosFlags.IgnoreZOrder | Win32.Enums.SetWindowPosFlags.IgnoreResize | Win32.Enums.SetWindowPosFlags.ShowWindow); } }
public async Task <bool> UnLock() { return(await Task.Run(() => { uint dummy = 0; var pmr = new Win32Functions.PREVENT_MEDIA_REMOVAL { PreventMediaRemoval = 0 }; return Win32Functions.DeviceIoControl(_driveHandle, Win32Functions.IOCTL_STORAGE_MEDIA_REMOVAL, pmr, (uint)Marshal.SizeOf(pmr), IntPtr.Zero, 0, ref dummy, IntPtr.Zero) == 0; })); }
private async Task <IntPtr> CreateDriveHandle() { return(await Task.Run(() => { var handle = Win32Functions.CreateFile("\\\\.\\" + _driveName + ':', Win32Functions.GENERIC_READ, Win32Functions.FILE_SHARE_READ, IntPtr.Zero, Win32Functions.OPEN_EXISTING, 0, IntPtr.Zero); if (IsValidHandle(handle)) { return handle; } throw new InvalidOperationException("Drive '" + _driveName + "' is currently opened."); })); }
private void WindowTitleCheckTimer_Tick(object sender, EventArgs e) { foreach (var window in MainWindows) { foreach (var tab in window.TabsContainer.Tabs) { try { tab.Title = DefaultWindowNames.NormalizeTitle(Win32Functions.GetWindowText(tab.HostedWindowItem.WindowHandle)); } catch { } } } }
public void SetWindowPosition(Window window) { var position = this.TranslatePoint(new Point(0, 0), window); var dpi = VisualTreeHelper.GetDpi(window); var winLeft = position.X * dpi.DpiScaleX; var winTop = position.Y * dpi.DpiScaleY; var winWidth = this.ActualWidth * dpi.DpiScaleX; var winHeight = this.ActualHeight * dpi.DpiScaleY; var result = Win32Functions.SetWindowPos(childRef, IntPtr.Zero, (int)winLeft, (int)winTop, (int)winWidth, (int)winHeight, Win32.Enums.SetWindowPosFlags.IgnoreZOrder | Win32.Enums.SetWindowPosFlags.IgnoreResize | Win32.Enums.SetWindowPosFlags.ShowWindow); }
protected override HandleRef BuildWindowCore(HandleRef hwndParent) { int style = Win32Functions.GetWindowLongPtr(childRef, Win32Functions.GWL_STYLE).ToInt32(); int newStyle = style & ~(Win32Functions.WS_MAXIMIZEBOX | Win32Functions.WS_MINIMIZEBOX | Win32Functions.WS_CAPTION | Win32Functions.WS_THICKFRAME); newStyle |= Win32Functions.WS_CHILD; Win32Functions.SetWindowLongPtr(new HandleRef(this, childRef), Win32Functions.GWL_STYLE, new IntPtr(newStyle)); Win32Functions.SetParent(childRef, hwndParent.Handle); return(new HandleRef(this, childRef)); }
private async Task ContainTargetWindow(HostedWindowItem item) { var target = item.WindowHandle; MyHost host; if ((App.Current as App).TargetWindowHosts.ContainsKey(target)) { host = (App.Current as App).TargetWindowHosts[target]; } else { host = new MyHost(target); (App.Current as App).TargetWindowHosts[target] = host; } if (host.Parent == null) { WindowContainer.Child = host; } else if (host.Parent != null && host.Parent != WindowContainer) { MessageBox.Show("ContainTargetWindow failed. The host has another parent."); return; } // TODO: Try to make it faster on console launch. But how? var dpi = VisualTreeHelper.GetDpi(this); if (item.Dpi != dpi.PixelsPerInchX) { ConsoleFunctions.SendDpiChangedMessage(target, (int)dpi.PixelsPerInchX); item.Dpi = dpi.PixelsPerInchX; } await Task.Delay(10); int style = Win32Functions.GetWindowLongPtr(target, Win32Functions.GWL_STYLE).ToInt32(); int newStyle = style & ~(Win32Functions.WS_CHILD); Win32Functions.SetWindowLongPtr(new HandleRef(this, target), Win32Functions.GWL_STYLE, new IntPtr(newStyle)); await Task.Delay(10); MaximizeWindow(target, Win32.Enums.ShowWindowCommands.Normal); Win32Functions.SetForegroundWindow(target); }
private async void Window_Activated(object sender, EventArgs e) { Debug.WriteLine("Activated"); await Task.Delay(100); if (!switchToContentEnabled) { return; } if (AppContextMenus.IsAContextMenuOpen || SettingsWindow.IsOpen) { return; } Win32Functions.SetForegroundWindow(CurrentContainedWindowHandle); }
private void MenuItemShowPropertiesDialogClick(object sender, RoutedEventArgs e) { if (LstViewData.SelectedIndex != -1) { try { var item = LstViewData.SelectedItem as TaskItemDetailed; if (item != null) { Win32Functions.ShowFileProperties(item.ProcessPath); } } catch (Exception exp) { Trace.WriteLine("Something Went Wrong! :" + exp.Message); } } }
private static void MaximizeWindow(IntPtr target, Win32.Enums.ShowWindowCommands cmd) { WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.Length = Marshal.SizeOf(placement); Win32Functions.GetWindowPlacement(target, ref placement); if (placement.ShowCmd != Win32.Enums.ShowWindowCommands.Maximize) { WINDOWPLACEMENT newPlacement = new WINDOWPLACEMENT { Length = Marshal.SizeOf(typeof(WINDOWPLACEMENT)), ShowCmd = cmd, MaxPosition = placement.MaxPosition, MinPosition = placement.MinPosition, NormalPosition = placement.NormalPosition, }; Win32Functions.SetWindowPlacement(target, ref newPlacement); } }
public async Task <TableOfContents> ReadTableOfContents() { if (!await IsCdInDrive()) { return(null); } return(await Task.Run(() => { var toc = new Win32Functions.CDROM_TOC(); uint bytesRead = 0; var succes = Win32Functions.DeviceIoControl(_driveHandle, Win32Functions.IOCTL_CDROM_READ_TOC, IntPtr.Zero, 0, toc, (uint)Marshal.SizeOf(toc), ref bytesRead, IntPtr.Zero) != 0; if (!succes) { throw new Exception("Reading the TOC failed."); } return TableOfContents.Create(toc); })); }
private void CreateDestroyWinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) { try { // Close tab if process exited if (eventType == Win32Functions.EVENT_OBJECT_DESTROY) { var allTabs = (from window in MainWindows from tab in window.TabsContainer.Tabs select(window, tab)).ToList(); foreach (var(window, tab) in allTabs) { if (tab.HostedWindowItem.WindowHandle == hwnd) { window.TabsContainer.CloseTab(tab.HostedWindowItem); } } } // Attach to new terminals if (eventType == Win32Functions.EVENT_OBJECT_CREATE && TabbedShell.Properties.Settings.Default.AttachToAllTerminalsEnabled) { var className = Win32Functions.GetClassName(hwnd); if (className == "ConsoleWindowClass") { Dispatcher.BeginInvoke(DispatcherPriority.Input, (Action)(() => { WaitForPotentialConsoleWindow(hwnd); })); } } } catch (Exception ex) { Debug.WriteLine("CreateDestroyWinEventProc: " + ex.ToString()); } }
public async Task <byte[]> ReadSector(int startSector, int numberOfSectors) { return(await Task.Run(() => { var rri = new Win32Functions.RAW_READ_INFO { TrackMode = Win32Functions.TRACK_MODE_TYPE.CDDA, SectorCount = (uint)numberOfSectors, DiskOffset = startSector *Constants.CB_CDROMSECTOR }; uint bytesRead = 0; var buffer = new byte[Constants.CB_AUDIO *numberOfSectors]; var success = Win32Functions.DeviceIoControl(_driveHandle, Win32Functions.IOCTL_CDROM_RAW_READ, rri, (uint)Marshal.SizeOf(rri), buffer, (uint)buffer.Length, ref bytesRead, IntPtr.Zero); if (success != 0) { return buffer; } throw new Exception("Failed to read from disk"); })); }
public static void OpenFind(HostedWindowItem console) { Win32Functions.PostMessage(console.WindowHandle, Win32Functions.WM_SYSCOMMAND, new IntPtr(SC_FIND_SECRET), IntPtr.Zero); }
public static void ForcePaint(this Window window) { var x = new WindowInteropHelper(window); Win32Functions.SendMessage(x.Handle, Win32Functions.WmPaint, IntPtr.Zero, IntPtr.Zero); }
private void SetWindowOpacity(IntPtr containedWindowHandle, double opacity) { Win32Functions.SetWindowLongPtr(new HandleRef(this, containedWindowHandle), Win32Functions.GWL_EXSTYLE, new IntPtr(Win32Functions.GetWindowLongPtr(containedWindowHandle, Win32Functions.GWL_EXSTYLE).ToInt32() | Win32Functions.WS_EX_LAYERED)); Win32Functions.SetLayeredWindowAttributes(containedWindowHandle, 0, (byte)(opacity * 255), Win32Functions.LWA_ALPHA); }
protected virtual void OnHookFailed(int Error) { throw Win32Functions.TranslateError(Error); }
private async void WaitForPotentialConsoleWindow(IntPtr hwnd) { var beginTime = DateTime.UtcNow; Win32Functions.GetWindowThreadProcessId(hwnd, out uint consoleProcessId); var consoleProcess = Process.GetProcessById((int)consoleProcessId); // Ignore 'wslhost' var processName = consoleProcess.ProcessName.ToLower(); if (processName == "wslhost") { return; } // Wait to see if it becomes visible do { int style = Win32Functions.GetWindowLongPtr(hwnd, Win32Functions.GWL_STYLE).ToInt32(); bool isVisible = ((style & Win32Functions.WS_VISIBLE) != 0); if (isVisible) { Debug.WriteLine("New console window detected! " + hwnd.ToString()); // Get window title var title = Win32Functions.GetWindowText(hwnd); // Get window position WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.Length = Marshal.SizeOf(placement); Win32Functions.GetWindowPlacement(hwnd, ref placement); try { await WindowContainSemaphore.WaitAsync(); // Ignore if the new window is ours var allHandles = from window in MainWindows from tab in window.TabsContainer.Tabs select tab.HostedWindowItem.WindowHandle; if (allHandles.Contains(hwnd)) { return; } System.Windows.Forms.Screen.PrimaryScreen.GetScaleFactors(out double scaleX, out double scaleY); var mainWindow = new MainWindow(hwnd, title, new Point(placement.NormalPosition.Left / scaleX, placement.NormalPosition.Top / scaleY), new Size(placement.NormalPosition.Width / scaleX, placement.NormalPosition.Height / scaleY)); mainWindow.Show(); } finally { WindowContainSemaphore.Release(); } return; } await Task.Delay(10); }while (DateTime.UtcNow - beginTime < TimeSpan.FromSeconds(2)); }