private IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handeled) { switch (msg) { case WM_GETMINMAXINFO: WmGetMinMaxInfo(hwnd, lParam); handeled = true; break; case WM_WINDOWPOSCHANGING: WINDOWPOS pos = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS)); if ((pos.flags & 0x0002) != 0) { return(IntPtr.Zero); } Window wnd = (Window)HwndSource.FromHwnd(hwnd).RootVisual; if (wnd == null) { return(IntPtr.Zero); } bool changedPos = false; PresentationSource source = PresentationSource.FromVisual(this); double wpfDpi = 96; double dpiX = wpfDpi; double dpiY = wpfDpi; if (source != null) { dpiX = wpfDpi * source.CompositionTarget.TransformToDevice.M11; dpiY = wpfDpi * source.CompositionTarget.TransformToDevice.M22; } int minWidth = (int)Math.Round(this.MinWidth / 96 * dpiX, 0); if (pos.cx < minWidth) { pos.cx = minWidth; changedPos = true; } int minHeight = (int)Math.Round(this.MinHeight / 96 * dpiY, 0); if (pos.cy < minHeight) { pos.cy = minHeight; changedPos = true; } if (!changedPos) { return(IntPtr.Zero); } Marshal.StructureToPtr(pos, lParam, true); handeled = true; break; } return((System.IntPtr) 0); }
private bool IsPresented() { return(PresentationSource.FromVisual(this) != null && ActualWidth > 0 && ActualHeight > 0); }
private void OnSourceInitialized(object sender, EventArgs e) { _hwndSource = (HwndSource)PresentationSource.FromVisual(this); }
private void WindowResize(object sender, MouseButtonEventArgs e) //PreviewMousLeftButtonDown { HwndSource hwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource; SendMessage(hwndSource.Handle, 0x112, (IntPtr)61448, IntPtr.Zero); }
public static Size TransformFromDevice(this Size size, Visual visual) { Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; return(new Size(size.Width * matrix.M11, size.Height * matrix.M22)); }
protected override void OnRender(DrawingContext dc) { Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice; double dpiFactor = 1 / m.M11; RenderOptions.SetEdgeMode(this, EdgeMode.Unspecified); Brush brushTextLabel = new SolidColorBrush((Color)FindResource("ColorControlLightBackground")); Brush brushBodyLine = IsDarkMode ? Brushes.Red : Brushes.Yellow; Brush brushBackground = IsDarkMode ? new SolidColorBrush(Color.FromRgb(20, 0, 0)) : new SolidColorBrush(Color.FromRgb(20, 20, 20)); Pen penBodyLine = new Pen(brushBodyLine, dpiFactor); double padding = 20; double radius = Math.Min(ActualWidth, ActualHeight) / 2 - padding; dc.DrawEllipse(brushBackground, null, new Point(ActualWidth / 2, ActualHeight / 2), radius, radius); if (ShowChart && bodyCoordinatesInterpolated != null) { Geometry clipGeometry = new EllipseGeometry(new Point(ActualWidth / 2, ActualHeight / 2), radius, radius); dc.PushClip(clipGeometry); var figure = new PathFigure(); double timeFrom = FromTime.TotalHours; double timeTo = ToTime.TotalHours; double obsDuration = timeTo < timeFrom ? timeTo - timeFrom + 24 : timeTo - timeFrom; int fromIndex = (int)(bodyCoordinatesInterpolated.Length / 24 * timeFrom); int count = Math.Max(1, (int)(bodyCoordinatesInterpolated.Length / 24 * obsDuration)); for (int i = fromIndex; i <= fromIndex + count; i++) { var c = bodyCoordinatesInterpolated[i > bodyCoordinatesInterpolated.Length - 1 ? i - bodyCoordinatesInterpolated.Length : i]; double angle = Angle.ToRadians(c.Azimuth - 90); double r = radius * (90 - c.Altitude) / 90; double x = ActualWidth / 2 + r * Math.Cos(angle); double y = ActualHeight / 2 - r * Math.Sin(angle); if (!figure.Segments.Any()) { figure.StartPoint = new Point(x, y); } figure.Segments.Add(new LineSegment(new Point(x, y), true)); } var geometry = new PathGeometry(); geometry.Figures.Add(figure); dc.DrawGeometry(null, penBodyLine, geometry); dc.Pop(); } string[] labels = new string[] { "S", "W", "N", "E" }; for (int i = 0; i < 4; i++) { var text = new FormattedText(Text.Get($"Planner.DirectionChart.{labels[i]}"), System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("Arial"), 10, brushTextLabel); double angle = Angle.ToRadians(i * 90 - 90); double r = radius + 5 + Math.Max(text.WidthIncludingTrailingWhitespace / 2, text.Height / 2); double x = ActualWidth / 2 + r * Math.Cos(angle); double y = ActualHeight / 2 - r * Math.Sin(angle); dc.DrawText(text, new Point(x - text.WidthIncludingTrailingWhitespace / 2, y - text.Height / 2)); } }
protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); simConnectAdapter.AttachWindow((HwndSource)PresentationSource.FromVisual(this)); }
private void HookWin32Message() { var source = PresentationSource.FromVisual(this) as HwndSource; source?.AddHook(WndProc); // Hook Win32 Messages to method }
/// <summary> /// Get cropping areas as BitmapFrame /// </summary> /// <returns></returns> public BitmapFrame GetCroppedBitmapFrame() { var parent = VisualTreeHelper.GetParent(_originalCanvas) as UIElement; // 1) get current dpi PresentationSource source = PresentationSource.FromVisual(Application.Current.MainWindow); Matrix matrix = source.CompositionTarget.TransformToDevice; double dpiX = matrix.M11 * 96; double dpiY = matrix.M22 * 96; // 2) create RenderTargetBitmap var elementBitmap = new RenderTargetBitmap(( int )_originalCanvas.ActualWidth, ( int )_originalCanvas.ActualHeight, dpiX, dpiY, PixelFormats.Pbgra32); elementBitmap = new RenderTargetBitmap(( int )_originalCanvas .RenderSize.Width, ( int )_originalCanvas .RenderSize.Height, dpiX, dpiY, PixelFormats.Default); //Important _originalCanvas.Measure(_originalCanvas.RenderSize); _originalCanvas.Arrange(new Rect(_originalCanvas.RenderSize)); // 3) draw element elementBitmap.Render(_originalCanvas); if (parent != null) { //Important parent.Measure(_originalCanvas.RenderSize); parent.Arrange(new Rect(_originalCanvas.RenderSize)); } var crop = new CroppedBitmap(elementBitmap, new Int32Rect(( int ) _rectangleManager .TopLeft.X, ( int ) _rectangleManager .TopLeft.Y, ( int ) _rectangleManager .RectangleWidth, ( int ) _rectangleManager .RectangleHeight)); return(BitmapFrame.Create(crop)); }
private static IntPtr GetHwnd(Popup popup) { var source = (HwndSource)PresentationSource.FromVisual(popup.Child); return(source.Handle); }
//MainWindow构造函数 public MainWindow() { #region "读取注册表(必须在初始化之前读取)" //背景图片 string bg = RegeditRW.RegReadString("Background"); double bgStretch = RegeditRW.RegRead("BackgroundStretch"); //透明度 double bgAlpha = RegeditRW.RegRead("BGAlpha"); double bgPanelAlpha = RegeditRW.RegRead("BGPanelAlpha"); double windowAlpha = RegeditRW.RegRead("WindowAlpha"); //窗口大小 double mainWindowHeight = RegeditRW.RegRead("MainWindowHeight"); double mainWindowWidth = RegeditRW.RegRead("MainWindowWidth"); //字体 string mainWindowFont = RegeditRW.RegReadString("MainWindowFont"); //设置菜单 double winTopmost = RegeditRW.RegRead("Topmost"); //游戏版本 double gameVersion = RegeditRW.RegRead("GameVersion"); #endregion //初始化 InitializeComponent(); //窗口缩放 SourceInitialized += delegate(object sender, EventArgs e) { _HwndSource = PresentationSource.FromVisual((Visual)sender) as HwndSource; }; MouseMove += new System.Windows.Input.MouseEventHandler(Window_MouseMove); //mainWindow初始化标志 MWInit = true; #region "读取设置" //设置字体 if (mainWindowFont == "" || mainWindowFont == null) { RegeditRW.RegWrite("MainWindowFont", "微软雅黑"); mainWindowFont = "微软雅黑"; } mainWindow.FontFamily = new FontFamily(mainWindowFont); //版本初始化 UI_Version.Text = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); //窗口可视化计时器 VisiTimer.Enabled = true; VisiTimer.Interval = 200; VisiTimer.Tick += new EventHandler(VisiTimerEvent); VisiTimer.Start(); //设置光标资源字典路径 cursorDictionary.Source = new Uri("Dictionary/CursorDictionary.xaml", UriKind.Relative); //显示窗口 MWVisivility = true; //右侧面板Visibility属性初始化 RightPanelVisibility("Welcome"); //窗口置顶 if (winTopmost == 1) { Se_button_Topmost_Click(null, null); } //设置背景 if (bg == "") { Se_BG_Alpha_Text.Foreground = Brushes.Silver; Se_BG_Alpha.IsEnabled = false; } else { Se_BG_Alpha_Text.Foreground = Brushes.Black; try { var brush = new ImageBrush() { ImageSource = new BitmapImage(new Uri(bg)) }; UI_BackGroundBorder.Background = brush; } catch { Visi.VisiCol(true, UI_BackGroundBorder); } } //设置背景拉伸方式 if (bgStretch == 0) { bgStretch = 2; } Se_ComboBox_Background_Stretch.SelectedIndex = (int)bgStretch - 1; //设置背景透明度 if (bgAlpha == 0) { bgAlpha = 101; } Se_BG_Alpha.Value = bgAlpha - 1; Se_BG_Alpha_Text.Text = "背景不透明度:" + (int)Se_BG_Alpha.Value + "%"; UI_BackGroundBorder.Opacity = (bgAlpha - 1) / 100; //设置面板透明度 if (bgPanelAlpha == 0) { bgPanelAlpha = 61; } Se_Panel_Alpha.Value = bgPanelAlpha - 1; Se_Panel_Alpha_Text.Text = "面板不透明度:" + (int)Se_Panel_Alpha.Value + "%"; RightGrid.Background.Opacity = (bgPanelAlpha - 1) / 100; //设置窗口透明度 if (windowAlpha == 0) { windowAlpha = 101; } Se_Window_Alpha.Value = windowAlpha - 1; Se_Window_Alpha_Text.Text = "窗口不透明度:" + (int)Se_Window_Alpha.Value + "%"; Opacity = (windowAlpha - 1) / 100; //设置高度和宽度 Width = mainWindowWidth; Height = mainWindowHeight; //设置游戏版本 UI_gameversion.SelectedIndex = (int)gameVersion; #endregion }
public static Point TransformFromDeviceDPI(this Visual visual, Point pt) { Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; return(new Point(pt.X * m.M11, pt.Y * m.M22)); }
public static Size TransformFromDeviceDPI(this Visual visual, Size size) { Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice; return(new Size(size.Width * m.M11, size.Height * m.M22)); }
public static bool CanTransform(this Visual visual) { return(PresentationSource.FromVisual(visual) != null); }
/// <summary> /// Displays the <see cref="TrayPopup"/> control if it was set. /// </summary> private void ShowTrayPopup(Point cursorPosition) { if (IsDisposed) { return; } // raise preview event no matter whether popup is currently set // or not (enables client to set it on demand) var args = RaisePreviewTrayPopupOpenEvent(); if (args.Handled) { return; } if (TrayPopup == null) { return; } // use absolute position, but place the popup centered above the icon TrayPopupResolved.Placement = PlacementMode.AbsolutePoint; TrayPopupResolved.HorizontalOffset = cursorPosition.X; TrayPopupResolved.VerticalOffset = cursorPosition.Y; // open popup TrayPopupResolved.IsOpen = true; IntPtr handle = IntPtr.Zero; if (TrayPopupResolved.Child != null) { // try to get a handle on the popup itself (via its child) HwndSource source = (HwndSource)PresentationSource.FromVisual(TrayPopupResolved.Child); if (source != null) { handle = source.Handle; } } // if we don't have a handle for the popup, fall back to the message sink if (handle == IntPtr.Zero) { handle = messageSink.MessageWindowHandle; } // activate either popup or message sink to track deactivation. // otherwise, the popup does not close if the user clicks somewhere else WinApi.SetForegroundWindow(handle); // raise attached event - item should never be null unless developers // changed the CustomPopup directly... if (TrayPopup != null) { RaisePopupOpenedEvent(TrayPopup); } // bubble routed event RaiseTrayPopupOpenEvent(); }
private static void ABSetPos(RegisterInfo info, Window appbarWindow, FrameworkElement childElement) { var edge = info.Edge; var barData = new Interop.APPBARDATA(); barData.cbSize = Marshal.SizeOf(barData); barData.hWnd = new WindowInteropHelper(appbarWindow).Handle; barData.uEdge = (int)edge; // Transforms a coordinate from WPF space to Screen space var toPixel = PresentationSource.FromVisual(appbarWindow).CompositionTarget.TransformToDevice; // Transforms a coordinate from Screen space to WPF space var toWpfUnit = PresentationSource.FromVisual(appbarWindow).CompositionTarget.TransformFromDevice; // Transform window size from wpf units (1/96 ") to real pixels, for win32 usage var sizeInPixels = (childElement != null ? toPixel.Transform(new Vector(childElement.ActualWidth, childElement.ActualHeight)) : toPixel.Transform(new Vector(appbarWindow.ActualWidth, appbarWindow.ActualHeight))); // Even if the documentation says SystemParameters.PrimaryScreen{Width, Height} return values in // "pixels", they return wpf units instead. var actualWorkArea = GetActualWorkArea(info); var screenSizeInPixels = toPixel.Transform(new Vector(actualWorkArea.Width, actualWorkArea.Height)); var workTopLeftInPixels = toPixel.Transform(new Point(actualWorkArea.Left, actualWorkArea.Top)); var workAreaInPixelsF = new Rect(workTopLeftInPixels, screenSizeInPixels); if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right) { barData.rc.top = (int)workAreaInPixelsF.Top; barData.rc.bottom = (int)workAreaInPixelsF.Bottom; if (barData.uEdge == (int)ABEdge.Left) { barData.rc.left = (int)workAreaInPixelsF.Left; //Left might not always be zero so we need to accommodate for that. //For example, if the Start Menu is docked LEFT, if we don't do the math, we'll end up with a negative size error barData.rc.right = barData.rc.left + (int)Math.Round(sizeInPixels.X); } else { barData.rc.right = (int)workAreaInPixelsF.Right; barData.rc.left = barData.rc.right - (int)Math.Round(sizeInPixels.X); } } else { barData.rc.left = (int)workAreaInPixelsF.Left; barData.rc.right = (int)workAreaInPixelsF.Right; if (barData.uEdge == (int)ABEdge.Top) { barData.rc.top = (int)workAreaInPixelsF.Top; //Top might not always be zero so we need to accommodate for that. //For example, if the Start Menu is docked TOP, if we don't do the math, we'll end up with a negative size error barData.rc.bottom = barData.rc.top + (int)Math.Round(sizeInPixels.Y); } else { barData.rc.bottom = (int)workAreaInPixelsF.Bottom; barData.rc.top = barData.rc.bottom - (int)Math.Round(sizeInPixels.Y); } } Interop.SHAppBarMessage((int)Interop.ABMsg.ABM_QUERYPOS, ref barData); Interop.SHAppBarMessage((int)Interop.ABMsg.ABM_SETPOS, ref barData); // transform back to wpf units, for wpf window resizing in DoResize. var location = toWpfUnit.Transform(new Point(barData.rc.left, barData.rc.top)); var dimension = toWpfUnit.Transform(new Vector( (barData.rc.right - barData.rc.left), (barData.rc.bottom - barData.rc.top))); // sometimes it calculates invalid new size, so ignore it if either X or Y is zero or negative. if (dimension.X <= 0 || dimension.Y <= 0) return; var rect = new Rect(location, new Size(dimension.X, dimension.Y)); info.DockedSize = rect; //This is done async, because WPF will send a resize after a new appbar is added. //if we size right away, WPFs resize comes last and overrides us. appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new ResizeDelegate(DoResize), appbarWindow, rect); }
/// <summary> /// 获得控件句柄 /// </summary> public static IntPtr GetVisualHandle(Visual visual) { return(((HwndSource)PresentationSource.FromVisual(visual)).Handle); }
/// <summary> /// Direct reference to the window pointer /// </summary> /// <returns></returns> protected HwndSource GetHWinSource() { return(PresentationSource.FromVisual(this) as HwndSource); }
public static bool IsAttachedToPresentationSource(this Visual element) { return(PresentationSource.FromVisual(element) != null); }
public MainWindow() { var connectedOk = true; GazeManager.Instance.Activate(GazeManager.ApiVersion.VERSION_1_0, GazeManager.ClientMode.Push); GazeManager.Instance.AddGazeListener(this); if (!GazeManager.Instance.IsActivated) { Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("EyeTribe Server has not been started"))); connectedOk = false; } /*else if (!GazeManager.Instance.IsCalibrated) * { * Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("User is not calibrated"))); * connectedOk = false; * }*/ if (!connectedOk) { Close(); return; } InitializeComponent(); // Check if multi-touch capability is available IsTouchEnabled = TouchHandler.DigitizerCapabilities.IsMultiTouchReady; if (IsTouchEnabled) { // Register for stylus (touch) events StylusDown += MainWindowStylusDown; StylusUp += MainWindowStylusUp; } // Register for mouse clicks PreviewMouseDown += TapDown; PreviewMouseUp += TapUp; // Register for key events KeyDown += WindowKeyDown; KeyUp += WindowKeyUp; // Get the current DIP scale dpiScale = CalcDpiScale(); // Hide all from start GridTop.Visibility = Visibility.Collapsed; scrollTimer = new Timer { Interval = 30, Enabled = true }; scrollTimer.Tick += ScrollTimerTick; Loaded += (sender, args) => { if (Screen.PrimaryScreen.Bounds.Width > MAX_IMAGE_WIDTH) { WebImage.Width = MAX_IMAGE_WIDTH * dpiScale; } else { WebImage.Width = Screen.PrimaryScreen.Bounds.Width * dpiScale; } // Transformation matrix that accomodate for the DPI settings var presentationSource = PresentationSource.FromVisual(this); transfrm = presentationSource.CompositionTarget.TransformFromDevice; // enable stylus (touch) events if (IsTouchEnabled) { Factory.EnableStylusEvents(this); } ExecuteSelectedButton("newyorktimes"); }; }
/// <summary> /// Connects the filters of a previously created graph /// (created by CreateGraph()). Once rendered the graph /// is ready to be used. This method may also destroy /// streams if we have streams we no longer want. /// </summary> protected void RenderGraph() { var didSomething = false; const int WS_CHILD = 0x40000000; const int WS_CLIPCHILDREN = 0x02000000; const int WS_CLIPSIBLINGS = 0x04000000; // Stop the graph MediaControl?.Stop(); // Create the graph if needed (group should already be created) CreateGraph(); // Derender the graph if we have a capture or preview stream // that we no longer want. We can't derender the capture and // preview streams seperately. // Notice the second case will leave a capture stream intact // even if we no longer want it. This allows the user that is // not using the preview to Stop() and Start() without // rerendering the graph. if (!WantPreviewRendered && IsPreviewRendered) { DerenderGraph(); } // Render preview stream (only if necessary) if (WantPreviewRendered && !IsPreviewRendered) { // Render preview (video -> renderer) var cat = Uuid.PinCategory.Preview; var med = Uuid.MediaType.Video; var hr = CaptureGraphBuilder.RenderStream(ref cat, ref med, VideoDeviceFilter, _baseGrabFlt, null); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } // Get the IVideoWindow interface VideoWindow = (ControlStreaming.IVideoWindow)GraphBuilder; // Set the video window to be a child of the main window var source = PresentationSource.FromVisual(PreviewWindow) as HwndSource; hr = VideoWindow.put_Owner(source.Handle); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } // Set video window style hr = VideoWindow.put_WindowStyle(WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } // Position video window in client rect of owner window PreviewWindow.SizeChanged += OnPreviewWindowResize; OnPreviewWindowResize(this, null); // Make the video window visible, now that it is properly positioned hr = VideoWindow.put_Visible(CoreStreaming.DsHlp.OATRUE); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } IsPreviewRendered = true; didSomething = true; var media = new CoreStreaming.AMMediaType(); hr = SampGrabber.GetConnectedMediaType(media); if (hr < 0) { Marshal.ThrowExceptionForHR(hr); } if ((media.formatType != Uuid.FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero)) { throw new NotSupportedException("Unknown Grabber Media Format"); } _videoInfoHeader = (EditStreaming.VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(EditStreaming.VideoInfoHeader)); Marshal.FreeCoTaskMem(media.formatPtr); media.formatPtr = IntPtr.Zero; } if (didSomething) { ActualGraphState = GraphState.Rendered; } }
public static void Init_WndProc(System.Windows.Window window, HwndSourceHook hwndSourceHook) { HwndSource source = PresentationSource.FromVisual(window) as HwndSource; source.AddHook(hwndSourceHook); }
public static Rect TransformFromDevice(this Rect rect, Visual visual) { Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; return(Rect.Transform(rect, matrix)); }
/// <summary> /// Displays the child window and collects results for <see cref="IInteractionRequest"/>. /// </summary> /// <param name="parameter">The parameter to the action. If the action does not require a parameter, the parameter may be set to a null reference.</param> protected override void Invoke(object parameter) { var args = parameter as InteractionRequestedEventArgs; if (args == null) { return; } // If the WindowContent shouldn't be part of another visual tree. if (this.WindowContent != null && this.WindowContent.Parent != null) { return; } Window wrapperWindow = this.GetWindow(args.Context); // We invoke the callback when the interaction's window is closed. var callback = args.Callback; EventHandler handler = null; handler = (o, e) => { wrapperWindow.Closed -= handler; wrapperWindow.Content = null; if (callback != null) { callback(); } }; wrapperWindow.Closed += handler; if (this.CenterOverAssociatedObject && this.AssociatedObject != null) { // If we should center the popup over the parent window we subscribe to the SizeChanged event // so we can change its position after the dimensions are set. SizeChangedEventHandler sizeHandler = null; sizeHandler = (o, e) => { wrapperWindow.SizeChanged -= sizeHandler; FrameworkElement view = this.AssociatedObject; // Position is the top left position of the view from which the request was initiated. // On multiple monitors, if the X or Y coordinate is negative it represent that the monitor from which // the request was initiated is either on the left or above the PrimaryScreen Point position = view.PointToScreen(new Point(0, 0)); PresentationSource source = PresentationSource.FromVisual(view); position = source.CompositionTarget.TransformFromDevice.Transform(position); // Find the middle of the calling view. // Take the width and height of the view divided by 2 and add to the X and Y coordinates. var middleOfView = new Point(position.X + (view.ActualWidth / 2), position.Y + (view.ActualHeight / 2)); // Set the coordinates for the top left part of the wrapperWindow. // Take the width of the wrapperWindow, divide it by 2 and substract it from // the X coordinate of middleOfView. Do the same thing for the Y coordinate. // If the wrapper window is wider or taller than the view, it will be behind the view. wrapperWindow.Left = middleOfView.X - (wrapperWindow.ActualWidth / 2); wrapperWindow.Top = middleOfView.Y - (wrapperWindow.ActualHeight / 2); }; wrapperWindow.SizeChanged += sizeHandler; } if (this.IsModal) { wrapperWindow.ShowDialog(); } else { wrapperWindow.Show(); } }
public static Point TransformFromDevice(this Point point, Visual visual) { Matrix matrix = PresentationSource.FromVisual(visual).CompositionTarget.TransformFromDevice; return(new Point(point.X * matrix.M11, point.Y * matrix.M22)); }
private void FillDpiCombobox() { double systemDpiScale; _isInternalChange = true; // We can get the system DPI scale from // PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice.M11 and M22 var presentationSource = PresentationSource.FromVisual(this); if (presentationSource != null && presentationSource.CompositionTarget != null) { // Theoretically we can have different x any y DPI scale so we make an average systemDpiScale = (presentationSource.CompositionTarget.TransformToDevice.M11 + presentationSource.CompositionTarget.TransformToDevice.M22) / 2; } else { systemDpiScale = 1.0; // This should not happen } // First entry is "System default" var systemDefaultComboBoxItem = new ComboBoxItem() { Content = string.Format(System.Globalization.CultureInfo.InvariantCulture, "System default - {0:0} DPI (scale: {1:0.0#})", 96.0 * systemDpiScale, systemDpiScale), Tag = double.NaN // Tag = DpiScale (NaN = system default) }; if (double.IsNaN(SelectedDpiScale)) { systemDefaultComboBoxItem.IsSelected = true; } DpiComboBox.Items.Add(systemDefaultComboBoxItem); foreach (var possibleDpiValue in _possibleDpiValues) { double scale = possibleDpiValue / 96.0; var comboBoxItem = new ComboBoxItem() { Content = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0:0} DPI (scale: {1:0.0#})", possibleDpiValue, scale), Tag = scale // Tag = DpiScale }; // ReSharper disable once CompareOfFloatsByEqualityOperator if (SelectedDpiScale == scale) { comboBoxItem.IsSelected = true; } DpiComboBox.Items.Add(comboBoxItem); } _isInternalChange = false; }
protected override void OnAttached() { if (PresentationSource.FromVisual(AssociatedObject) != null) { AddHwndHook(); } else { AssociatedObject.SourceInitialized += AssociatedObject_SourceInitialized; } if (AllowsTransparency && EnableDWMDropShadow) { throw new InvalidOperationException("EnableDWMDropShadow cannot be set to True when AllowsTransparency is True."); } AssociatedObject.WindowStyle = WindowStyle.None; if (!AssociatedObject.IsLoaded) { try { AssociatedObject.AllowsTransparency = AllowsTransparency; } catch (Exception) { //For some reason, we can't determine if the window has loaded or not. So we will swallow the exception. } } AssociatedObject.StateChanged += AssociatedObjectStateChanged; AssociatedObject.SetValue(WindowChrome.GlassFrameThicknessProperty, new Thickness(-1)); var window = AssociatedObject as MetroWindow; if (window != null) { AssociatedObject.Activated += (s, e) => HandleMaximize(); //MetroWindow already has a border we can use AssociatedObject.Loaded += (s, e) => { var ancestors = window.GetPart <Border>("PART_Border"); Border = ancestors; if (ShouldHaveBorder()) { AddBorder(); } var titleBar = window.GetPart <Grid>("PART_TitleBar"); if (titleBar != null) { titleBar.SetValue(WindowChrome.IsHitTestVisibleInChromeProperty, true); } var windowCommands = window.GetPart <ContentPresenter>("PART_WindowCommands"); if (windowCommands != null) { windowCommands.SetValue(WindowChrome.IsHitTestVisibleInChromeProperty, true); } var windowButtonCommands = window.GetPart <ContentControl>("PART_WindowButtonCommands"); if (windowButtonCommands != null) { windowButtonCommands.SetValue(WindowChrome.IsHitTestVisibleInChromeProperty, true); } }; switch (AssociatedObject.ResizeMode) { case ResizeMode.NoResize: window.ShowMaxRestoreButton = false; window.ShowMinButton = false; ResizeWithGrip = false; break; case ResizeMode.CanMinimize: window.ShowMaxRestoreButton = false; ResizeWithGrip = false; break; case ResizeMode.CanResize: ResizeWithGrip = false; break; case ResizeMode.CanResizeWithGrip: ResizeWithGrip = true; break; } } else { //Other windows may not, easiest to just inject one! var content = (UIElement)AssociatedObject.Content; AssociatedObject.Content = null; Border = new Border { Child = content, BorderBrush = new SolidColorBrush(Colors.Black) }; AssociatedObject.Content = Border; } if (ResizeWithGrip) { AssociatedObject.ResizeMode = ResizeMode.CanResizeWithGrip; } if (AutoSizeToContent) { AssociatedObject.Loaded += (s, e) => { //Temp fix, thanks @lynnx AssociatedObject.SizeToContent = SizeToContent.Height; AssociatedObject.SizeToContent = AutoSizeToContent ? SizeToContent.WidthAndHeight : SizeToContent.Manual; } } ; base.OnAttached(); }
private async void RegionClickCanvas_MouseUp(object sender, MouseButtonEventArgs e) { isSelecting = false; Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice; var mPt = GetMousePos(); System.Windows.Point movingPoint = e.GetPosition(this); movingPoint.X *= m.M11; movingPoint.Y *= m.M22; movingPoint.X = Math.Round(movingPoint.X); movingPoint.Y = Math.Round(movingPoint.Y); if (mPt == movingPoint) { Debug.WriteLine("Probably on Screen 1"); } double correctedLeft = this.Left; double correctedTop = this.Top; if (correctedLeft < 0) { correctedLeft = 0; } if (correctedTop < 0) { correctedTop = 0; } double xDimScaled = (Canvas.GetLeft(selectBorder) * m.M11); double yDimScaled = (Canvas.GetTop(selectBorder) * m.M22); Rectangle regionScaled = new Rectangle( (int)xDimScaled, (int)yDimScaled, (int)(selectBorder.Width * m.M11), (int)(selectBorder.Height * m.M22)); string grabbedText = ""; // remove selectBorder before capture - force screen Re-render to actually remove it try { RegionClickCanvas.Children.Remove(selectBorder); } catch { } RegionClickCanvas.Background.Opacity = 0; RegionClickCanvas.UpdateLayout(); RegionClickCanvas.Dispatcher.Invoke(() => { }, DispatcherPriority.Render); if (regionScaled.Width < 3 || regionScaled.Height < 3) { grabbedText = await GetClickedWord(new System.Windows.Point(xDimScaled, yDimScaled)); } else { grabbedText = await GetRegionsText(regionScaled); } if (string.IsNullOrWhiteSpace(grabbedText) == false) { Clipboard.SetText(grabbedText); if (Settings.Default.ShowToast) { ShowToast(grabbedText); } App.Current.Shutdown(); } else { RegionClickCanvas.Background.Opacity = .2; } }
void Timer_Elapsed(object sender, ElapsedEventArgs e) { if (Dispatcher.Thread != Thread.CurrentThread) { Dispatcher.BeginInvoke(new EventHandler <ElapsedEventArgs>(Timer_Elapsed), new object[] { sender, e }); return; } try { Point curMousePos = m_lastItemOver != null?Win32Calls.GetPosition(m_lastItemOver) : new Point(-1, -1); if (m_lastItemOver != null && new Rect(0, 0, m_lastItemOver.ActualWidth, m_lastItemOver.ActualHeight).Contains(curMousePos)) { TimeSpan ts = DateTime.Now - m_timerTime; if (ts.TotalMilliseconds > 500 || Mouse.LeftButton == MouseButtonState.Pressed) { ShowPopup(); m_lastItemOver.IsChecked = true; m_lastItemOver = null; m_timerTime = DateTime.Now; } m_timer.Start(); } else { var app = Application.Current; if (app == null) { return; } var window = app.MainWindow; if (window == null || !window.IsActive) { return; } if (PART_Popup.IsOpen && !PART_Popup.Resizing) { Win32Calls.Win32Point pt32 = new Win32Calls.Win32Point(); Win32Calls.GetCursorPos(ref pt32); Point mousePos = new Point(pt32.X, pt32.Y); Point pos = PointToScreen(new Point(0, 0)); Matrix m = PresentationSource.FromVisual(Window.GetWindow(this)).CompositionTarget.TransformToDevice; if (m != Matrix.Identity) { m.Invert(); mousePos = m.Transform(mousePos); pos = m.Transform(pos); } switch (TabsPlacement) { case System.Windows.Controls.Dock.Top: pos.Y += ActualHeight; break; case System.Windows.Controls.Dock.Bottom: pos.Y -= PART_Popup.Height; break; case System.Windows.Controls.Dock.Left: pos.X += ActualWidth; break; case System.Windows.Controls.Dock.Right: pos.X -= PART_Popup.Width; break; } bool b2 = new Rect(pos.X, pos.Y, PART_Popup.Width, PART_Popup.Height).Contains(mousePos); Point posThis = Win32Calls.GetPosition(this); bool b3 = new Rect(0, 0, ActualWidth, ActualHeight).Contains(posThis); if (!b2 && !b3) { TimeSpan ts = DateTime.Now - m_timerTime; if (ts.TotalMilliseconds > 1000) { // if mouse is outside for more than some time, then collapse this popup ClosePopup(); } else { m_timer.Start(); } } else { m_timerTime = DateTime.Now; m_timer.Start(); } } } } catch (InvalidOperationException) { // Can be thrown when closing the application and popup is still open... } }
/// <summary> /// Credit the code below to https://engy.us/blog/2020/01/01/implementing-a-custom-window-title-bar-in-wpf/ /// </summary> /// <param name="hwnd"></param> /// <param name="msg"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <param name="handled"></param> /// <returns></returns> protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); ((HwndSource)PresentationSource.FromVisual(this)).AddHook(HookProc); }