/// <summary> /// 注册 /// </summary> /// <param name="hWnd">需要捕获手柄消息的窗口</param> /// <param name="joystickId">要捕获的手柄Id</param> public bool Register(IntPtr hWnd, int joystickId) { bool flag = false; int result = 0; API.JOYCAPS caps = new API.JOYCAPS(); if (API.joyGetNumDevs() != 0) { //拥有手柄.则判断手柄状态 result = API.joyGetDevCaps(joystickId, ref caps, Marshal.SizeOf(typeof(API.JOYCAPS))); if (result == API.JOYERR_NOERROR) { //手柄处于正常状态 flag = true; } } if (flag) { //注册消息 if (!this.IsRegister) { _HWndSource = HwndSource.FromHwnd(hWnd); _HWndSource.AddHook(WndProc); //Application.AddMessageFilter(this); } this.IsRegister = true; result = API.joySetCapture(hWnd, joystickId, caps.wPeriodMin * 2, false); if (result != API.JOYERR_NOERROR) { flag = false; } } return(flag); }
public MainWindow() { InitializeComponent(); SourceInitialized += (s, e) => { IntPtr handle = (new WindowInteropHelper(this)).Handle; HwndSource.FromHwnd(handle).AddHook(WindowProc); }; MinimizeButton.Click += (s, e) => WindowState = WindowState.Minimized; MaximizeButton.Click += (s, e) => WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized; CloseButton.Click += (s, e) => Close(); _productRepository = new ProductRepository(); fileImportData = CompositeProductFileImport.Builder() .registerStrategy(new JsonFileImport()) .registerStrategy(new CsvFileImport()) .build(); _charts = new Charts(); _importDataPage = new ImportDataPage(_productRepository, fileImportData); _manageDataPage = new ManageDataPage(_productRepository); //_visualizeDataPage = new VisualizeDataPage(_productRepository); _mainFrame.Navigate(_importDataPage); }
// bring the window to top when users click in the non-client area. protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); // The non-focusable trick is buggy for Windows 7 and 8 // https://github.com/QL-Win/QuickLook/issues/644#issuecomment-628921704 if (App.IsWin10) { this.SetNoactivate(); HwndSource.FromHwnd(new WindowInteropHelper(this).Handle)?.AddHook( (IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) => { switch (msg) { case 0x0112: // WM_SYSCOMMAND this.BringToFront(false); break; } return(IntPtr.Zero); }); } }
/// <summary> /// 注册 /// </summary> /// <param name="window"></param> public static void RegisterDesktop(Window window) { WindowInteropHelper helper = new WindowInteropHelper(window); HwndSource mainWindowSrc = (HwndSource)HwndSource.FromHwnd(helper.Handle); APPBARDATA abd = new APPBARDATA(); abd.cbSize = (uint)Marshal.SizeOf(abd); abd.hWnd = mainWindowSrc.Handle; abd.uEdge = 2; abd.rc.top = 0; abd.rc.bottom = (int)SystemParameters.PrimaryScreenHeight; abd.rc.right = (int)SystemParameters.PrimaryScreenWidth; abd.rc.left = abd.rc.right - (int)window.ActualWidth; //注册新的应用栏,并指定系统应用于向应用栏发送通知消息的消息标识符。 SHAppBarMessage((UInt32)AppBarMessages.New, ref abd); //请求应用栏的大小和屏幕位置。 SHAppBarMessage((UInt32)AppBarMessages.QueryPos, ref abd); //设置应用栏的大小和屏幕位置。 SHAppBarMessage((UInt32)AppBarMessages.SetPos, ref abd); //设置应用所在平面位置。 MoveWindow(abd.hWnd, abd.rc.left, abd.rc.top, abd.rc.right - abd.rc.left, abd.rc.bottom - abd.rc.top, 1); }
private void Window_SourceInitialized(object sender, EventArgs e) { Top = 0; helper = new WindowInteropHelper(this); HwndSource.FromHwnd(helper.Handle).AddHook(new HwndSourceHook(WndProc)); if (Settings.EnableDesktop && Icons == null) { grid.Children.Add(Icons = new DesktopIcons()); if (Settings.EnableDynamicDesktop) { TryAndEat(() => { DesktopNavigationToolbar nav = new DesktopNavigationToolbar() { Owner = this }; nav.Show(); }); } } SetupPostInit(); }
/// <summary> /// Attach a DpiHandler to the specified window /// </summary> /// <param name="window">Windows</param> /// <param name="dpiHandler">DpiHandler</param> private static void AttachDpiHandler(Window window, DpiHandler dpiHandler) { var windowInteropHelper = new WindowInteropHelper(window); // Due to the nature of the WPF Window, we cannot get to the WM_NCCREATE event from outside // The SourceInitialized event is actually called when this event happens. window.SourceInitialized += (sender, args) => { DpiHandler.TryEnableNonClientDpiScaling(windowInteropHelper.Handle); // Get the HwndSource for the window, this works very early in the process by calling EnsureHandle (which creates the handle) var hwndSource = HwndSource.FromHwnd(windowInteropHelper.Handle); if (hwndSource == null) { throw new NotSupportedException("No HwndSource available, although EnsureHandle was called?"); } hwndSource.AddHook(dpiHandler.HandleWindowMessages); dpiHandler.MessageHandler = hwndSource; // Add the layout transform action dpiHandler.OnDpiChanged.Subscribe(dpi => window.UpdateLayoutTransform(dpi / DpiHandler.DefaultScreenDpi)); // Apply scaling window.UpdateLayoutTransform(DpiHandler.GetDpi(windowInteropHelper.Handle) / DpiHandler.DefaultScreenDpi); }; }
public static void ExtendGlass(Window win, int left, int right, int top) { // Obtain the window handle for WPF application var windowInterop = new WindowInteropHelper(win); var windowHandle = windowInterop.Handle; var mainWindowSrc = HwndSource.FromHwnd(windowHandle); if (mainWindowSrc != null) { if (mainWindowSrc.CompositionTarget != null) { mainWindowSrc.CompositionTarget.BackgroundColor = Colors.Transparent; } var margins = GetDpiAdjustedMargins(windowHandle, left, right, top); var returnVal = DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins); if (returnVal < 0) { throw new NotSupportedException("Operation failed."); } } }
public static void SetSidebar(Window wnd, AppBarSide side, bool topMost, bool overlapTaskBar, string scrnName) { MainWindow = wnd; Handle = new WindowInteropHelper(wnd).Handle; Side = side; ScreenName = scrnName; Screen = Utils.GetScreenFromName(scrnName); if (topMost) { AlwaysTop = topMost; AppbarNew(); if (!IsOverlapping && overlapTaskBar && side == AppBarSide.Right) { OverlapTaskbar(); } SizeAppbar(); wnd.Topmost = true; } else { AlwaysTop = topMost; wnd.Topmost = false; if (IsOverlapping && side == AppBarSide.Right) { RestoreTaskbar(); } SetPos(); } if (!WindowHooksAdded) { HwndSource.FromHwnd(Handle).AddHook(new HwndSourceHook(WndProc)); HwndSource.FromHwnd(Handle).AddHook(new HwndSourceHook(DwmManager.WndProc)); WindowHooksAdded = true; } }
private void DockAppBar(DockEdge edge, WorkArea windowWA, WorkArea appbarWA) { APPBARDATA _data = NewData(); _data.uEdge = (int)edge; _data.rc = new RECT() { Left = (int)Math.Round(appbarWA.Left), Top = (int)Math.Round(appbarWA.Top), Right = (int)Math.Round(appbarWA.Right), Bottom = (int)Math.Round(appbarWA.Bottom) }; NativeMethods.SHAppBarMessage(APPBARMSG.ABM_QUERYPOS, ref _data); NativeMethods.SHAppBarMessage(APPBARMSG.ABM_SETPOS, ref _data); appbarWA.Left = _data.rc.Left; appbarWA.Top = _data.rc.Top; appbarWA.Right = _data.rc.Right; appbarWA.Bottom = _data.rc.Bottom; AppBarWidth = appbarWA.Width; _source = HwndSource.FromHwnd(_data.hWnd); Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, (Action)(() => { Top = windowWA.Top; Left = windowWA.Left; Width = windowWA.Width; Height = windowWA.Height; _source.AddHook(AppBarHook); })); }
/// <summary> /// Override for glass look and feel /// </summary> /// <param name="e"></param> protected override void OnSourceInitialized(System.EventArgs e) { base.OnSourceInitialized(e); try { // This can not be done any earlier than the SourceInitialized event: GlassHelper.ExtendGlassFrame(this, new Thickness(-1)); // Attach a window procedure in order to detect later enabling of desktop composition IntPtr hwnd = new WindowInteropHelper(this).Handle; var hwndSource = HwndSource.FromHwnd(hwnd); if (hwndSource != null) { hwndSource.AddHook(new HwndSourceHook(WndProc)); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
bool System.Windows.Interop.IKeyboardInputSink.OnMnemonic(ref MSG msg, ModifierKeys modifiers) { switch (msg.message) { case 262: case 263: { string str = new string((char)((int)msg.wParam), 1); if (str == null || str.Length <= 0) { break; } IntPtr owner = (new WindowInteropHelper(this.Window)).Owner; HwndSource hwndSource = HwndSource.FromHwnd(owner); if (hwndSource == null || !AccessKeyManager.IsKeyRegistered(hwndSource, str)) { break; } AccessKeyManager.ProcessKey(hwndSource, str, false); return(true); } } return(false); }
public static Boolean ExtendGlassFrame(Window window, Thickness margin) { if (!(IsDwmIsCompositionEnabled())) { return(false); } IntPtr hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) { throw new InvalidOperationException(Resources.VistaAeroAPI_ExtendGlassFrame_The_Window_must_be_shown_before_extending_glass_); } window.Background = Brushes.Transparent; // ReSharper disable PossibleNullReferenceException HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent; // ReSharper restore PossibleNullReferenceException var margins = new MarginStruct(margin); DwmExtendFrameIntoClientArea(hwnd, ref margins); return(true); }
void StartWndProcHandler() { IntPtr hwnd = IntPtr.Zero; Window myWin = Application.Current.MainWindow; try { hwnd = new WindowInteropHelper(myWin).Handle; } catch (Exception ex) { Console.WriteLine(ex); } //Get the Hwnd source HwndSource source = HwndSource.FromHwnd(hwnd); //Win32 queue sink source.AddHook(new HwndSourceHook(WndProc)); id = new RawStuff.InputDevice(source.Handle); NumberOfKeyboards = id.EnumerateDevices(); id.KeyPressed += new RawStuff.InputDevice.DeviceEventHandler(_KeyPressed); }
/// <summary> /// ウインドウが生成された後の処理で、独自の WndProc を追加する /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RibbonWindow_Loaded(object sender, RoutedEventArgs e) { // I/O ボードのI/O変化はウインドウに対するメッセージという形で通知されるため // メッセージをフックするために使用します。 HwndSource src = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); src.AddHook(new HwndSourceHook(WndProc)); this.DataContext = _viewModel; WordModel.Vm = _viewModel; object obj = ModelData; VM.PythonConsole = pythonConsole; comboBox1.SelectedIndex = 0; //ステータス取得用のタイマーイベントを設定 _timer = new System.Windows.Threading.DispatcherTimer(System.Windows.Threading.DispatcherPriority.Normal, this.Dispatcher); _timer.Interval = TimeSpan.FromSeconds(0.1); _timer.Tick += new EventHandler(TimerFunc); //タイマーの開始はスクリプトのロードが完了してからにする // _timer.Start(); }
public Hotkey(Window handlerWindow, Action hotKeyHandler, Keys key, HotKeyModifiers modifiers) { m_onHotKeyPressed = hotKeyHandler; // Create a unique Id for this class in this instance string atomName = Thread.CurrentThread.ManagedThreadId.ToString("X8") + GetType().FullName; HotkeyID = Win32.GlobalAddAtom(atomName); // Set up the hook to listen for hot keys m_windowHandle = new WindowInteropHelper(handlerWindow).EnsureHandle(); if (m_windowHandle == null) { throw new ApplicationException( "Cannot find window handle. Try calling this on or after OnSourceInitialized()" ); } HwndSource source = HwndSource.FromHwnd(m_windowHandle); source.AddHook(HwndHook); ListenForHotKey(key, modifiers); }
public ColorWindow(ColorViewModel vm) { #region Set ower revit window for Wpf form if (!ColorViewModel.IsOpen) //Enforce single window { InitializeComponent(); Instance = this; var uiapp = ColorViewModel.Uiapp; IntPtr revitWindow; #if REVIT2018 revitWindow = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; // 2018 #else revitWindow = uiapp.MainWindowHandle; //Revit 2019 and above #endif //Get window of Revit form Revit handle HwndSource hwndSource = HwndSource.FromHwnd(revitWindow); var windowRevitOpen = hwndSource.RootVisual as Window; #endregion this.Owner = windowRevitOpen; //Set onwer for WPF window this.DataContext = vm; if (vm.DisplayUI()) { this.Show(); //Modeless form } } //Check: if Wpf window is minimized, re-open it if (Instance?.WindowState == WindowState.Minimized) { Instance.WindowState = WindowState.Normal; } }
private void OnUnloaded(object sender, RoutedEventArgs e) { if (!_loaded) { return; } _loaded = false; FancyBackgroundManager.Instance.RemoveListener(this); AboutHelper.Instance.PropertyChanged -= OnAboutPropertyChanged; if (_hook == null) { return; } try { HwndSource.FromHwnd(new WindowInteropHelper(this).Handle)?.RemoveHook(_hook); } catch (Exception) { Logging.Warning("Can’t remove one-instance hook"); } _hook = null; }
public static void RepairWpfWindowFullScreenBehavior(Window wpfWindow) { if (wpfWindow == null) { return; } if (wpfWindow.WindowState == WindowState.Maximized) { wpfWindow.WindowState = WindowState.Normal; wpfWindow.Loaded += delegate { wpfWindow.WindowState = WindowState.Maximized; }; } wpfWindow.SourceInitialized += delegate { IntPtr handle = (new WindowInteropHelper(wpfWindow)).Handle; HwndSource source = HwndSource.FromHwnd(handle); if (source != null) { source.AddHook(WindowProc); } }; }
private void MainWindow_OnSourceInitialized(object sender, EventArgs e) { if (_noAero) { return; } try { if ((_hwnd = new WindowInteropHelper(this).Handle) == IntPtr.Zero) { throw new InvalidOperationException("Could not get window handle for the main window."); } _hsource = HwndSource.FromHwnd(_hwnd); _hsource?.AddHook(WndProc); AdjustWindowFrame(); } catch (InvalidOperationException) { FallbackPaint(); } }
public static bool ExtendGlassFrame(Window window, Thickness margin) { if (!DwmIsCompositionEnabled()) { return(false); } IntPtr hwnd = new WindowInteropHelper(window).Handle; if (hwnd == IntPtr.Zero) { throw new InvalidOperationException( "The Window must be shown before extending glass."); } // Set the background to transparent from both the WPF and Win32 perspectives window.Background = Brushes.Transparent; HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor = Colors.Transparent; MARGINS margins = new MARGINS(margin); DwmExtendFrameIntoClientArea(hwnd, ref margins); return(true); }
public MainWindow() { InitializeComponent(); SourceInitialized += (s, e) => { IntPtr handle = (new WindowInteropHelper(this)).Handle; HwndSource.FromHwnd(handle).AddHook(new HwndSourceHook(WindowProc)); }; Loaded += (s, e) => { EnableBlur(); HandleTabletMode(); if (WindowsIdentity.GetCurrent() != null && WindowsIdentity.GetCurrent().User != null) { var managementEventWatcher = new ManagementEventWatcher(new EventQuery(string.Format(@"SELECT * FROM RegistryValueChangeEvent WHERE Hive='HKEY_USERS' AND KeyPath='{0}\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\ImmersiveShell' AND ValueName='TabletMode'", WindowsIdentity.GetCurrent().User.Value))); managementEventWatcher.EventArrived += (sI, eI) => Dispatcher.Invoke(() => HandleTabletMode()); managementEventWatcher.Start(); } }; CloseButton.Click += (s, e) => Close(); MaximizeButton.Click += (s, e) => WindowState = WindowState == WindowState.Normal ? WindowState.Maximized : WindowState.Normal; MinimizeButton.Click += (s, e) => SystemCommands.MinimizeWindow(this); StateChanged += (s, e) => Dispatcher.Invoke(() => (MaximizeButton.Content as PackIcon).Kind = WindowState == WindowState.Maximized ? PackIconKind.ChevronDown : PackIconKind.CropSquare); }
private void DesktopToolbar_SourceInitialized(object sender, EventArgs e) { helper = new WindowInteropHelper(this); HwndSource.FromHwnd(helper.Handle).AddHook(new HwndSourceHook(WndProc)); Shell.HideWindowFromTasks(helper.Handle); }
public NonClientMouseTracker(Window wnd) { _handle = new WindowInteropHelper(wnd).Handle; HwndSource.FromHwnd(_handle).AddHook(new HwndSourceHook(WndProc)); }
private HotKeyHandler(IntPtr hWnd) { this.hWnd = hWnd; source = HwndSource.FromHwnd(hWnd); }
internal static Window FromHwnd(IntPtr hwnd) { return(hwnd != IntPtr.Zero ? HwndSource.FromHwnd(hwnd)?.RootVisual as Window : null); }
public void PowerManagementRegistration(Window window, ISystemState systemState) { SystemState = systemState; PowerManager.RegisterMonitorStatusChange(window); HwndSource.FromHwnd(new WindowInteropHelper(window).Handle).AddHook(WndProc); }
// Start listening to clipboard events. Cannot be called before the window is initialized! public void Start() { windowHandle = new WindowInteropHelper(Window).EnsureHandle(); HwndSource.FromHwnd(windowHandle)?.AddHook(HwndHandler); NativeMethods.AddClipboardFormatListener(windowHandle); }
private static bool _ExtendGlassFrameInternal(Window window, Thickness margin) { Assert.IsNotNull(window); Assert.IsTrue(window.CheckAccess()); // Expect that this might be called on OSes other than Vista. if (!Utility.IsOSVistaOrNewer) { // Not an error. Just not on Vista so we're not going to get glass. return(false); } IntPtr hwnd = new WindowInteropHelper(window).Handle; if (IntPtr.Zero == hwnd) { throw new InvalidOperationException("Window must be shown before extending glass."); } HwndSource hwndSource = HwndSource.FromHwnd(hwnd); bool isGlassEnabled = NativeMethods.DwmIsCompositionEnabled(); if (!isGlassEnabled) { window.Background = SystemColors.WindowBrush; hwndSource.CompositionTarget.BackgroundColor = SystemColors.WindowColor; } else { // Apply the transparent background to both the Window and the HWND window.Background = Brushes.Transparent; hwndSource.CompositionTarget.BackgroundColor = Colors.Transparent; // Thickness is going to be DIPs, need to convert to system coordinates. Point deviceTopLeft = DpiHelper.LogicalPixelsToDevice(new Point(margin.Left, margin.Top)); Point deviceBottomRight = DpiHelper.LogicalPixelsToDevice(new Point(margin.Right, margin.Bottom)); var dwmMargin = new MARGINS { // err on the side of pushing in glass an extra pixel. cxLeftWidth = (int)Math.Ceiling(deviceTopLeft.X), cxRightWidth = (int)Math.Ceiling(deviceBottomRight.X), cyTopHeight = (int)Math.Ceiling(deviceTopLeft.Y), cyBottomHeight = (int)Math.Ceiling(deviceBottomRight.Y), }; NativeMethods.DwmExtendFrameIntoClientArea(hwnd, ref dwmMargin); } // Even if glass isn't currently enabled, add the hook so we can appropriately respond // if that changes. bool addHook = !_extendedWindows.ContainsKey(hwnd); if (addHook) { HwndSourceHook hook = delegate(IntPtr innerHwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (WM.DWMCOMPOSITIONCHANGED == (WM)msg) { _ExtendGlassFrameInternal(window, margin); handled = false; } return(IntPtr.Zero); }; _extendedWindows.Add(hwnd, hook); hwndSource.AddHook(hook); window.Closing += _OnExtendedWindowClosing; } return(isGlassEnabled); }
private static bool _SetWindowThemeAttribute(Window window, bool showCaption, bool showIcon) { bool isGlassEnabled; Assert.IsNotNull(window); Assert.IsTrue(window.CheckAccess()); // This only is expected to work if Aero glass is enabled. try { isGlassEnabled = NativeMethods.DwmIsCompositionEnabled(); } catch (DllNotFoundException) { // Not an error. Just not on Vista so we're not going to get glass. return(false); } IntPtr hwnd = new WindowInteropHelper(window).Handle; if (IntPtr.Zero == hwnd) { throw new InvalidOperationException("Window must be shown before we can modify attributes."); } var options = new WTA_OPTIONS { dwMask = (WTNCA.NODRAWCAPTION | WTNCA.NODRAWICON) }; if (isGlassEnabled) { if (!showCaption) { options.dwFlags |= WTNCA.NODRAWCAPTION; } if (!showIcon) { options.dwFlags |= WTNCA.NODRAWICON; } } NativeMethods.SetWindowThemeAttribute(hwnd, WINDOWTHEMEATTRIBUTETYPE.WTA_NONCLIENT, ref options, WTA_OPTIONS.Size); bool addHook = !_attributedWindows.ContainsKey(hwnd); if (addHook) { HwndSourceHook hook = delegate(IntPtr unusedHwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (WM.DWMCOMPOSITIONCHANGED == (WM)msg) { _SetWindowThemeAttribute(window, showCaption, showIcon); handled = false; } return(IntPtr.Zero); }; _attributedWindows.Add(hwnd, hook); HwndSource.FromHwnd(hwnd).AddHook(hook); window.Closing += _OnAttributedWindowClosing; } return(isGlassEnabled); }
public static void RemoveHook(this Window window, HwndSourceHook hook) { var source = HwndSource.FromHwnd(new WindowInteropHelper(window).Handle); source.RemoveHook(hook); }