Возьмите GestureDetector
на верхнем уровне всех виджетов и onTap()
этого gestureDetector
и вызовите
FocusScope.of(context).requestFocus(new FocusNode());
Screen.FromControl
, Screen.FromPoint
и Screen.FromRectangle
должны помочь вам в этом. Например, в WinForms это будет:
class MyForm : Form
{
public Rectangle GetScreen()
{
return Screen.FromControl(this).Bounds;
}
}
Я не знаю эквивалентного вызова WPF. Поэтому вам нужно сделать что-то вроде этого метода расширения.
static class ExtensionsForWPF
{
public static System.Windows.Forms.Screen GetScreen(this Window window)
{
return System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(window).Handle);
}
}
Остерегайтесь масштабного коэффициента ваших окон (100% / 125% / 150% / 200%). Вы можете получить реальный размер экрана, используя следующий код:
SystemParameters.FullPrimaryScreenHeight
SystemParameters.FullPrimaryScreenWidth
Добавить в ffpf
Screen.FromControl(this).Bounds
Вы можете использовать это, чтобы получить границы рабочего пространства рабочего стола основного экрана:
System.Windows.SystemParameters.WorkArea
Это также полезно для получения только размера основного экрана:
System.Windows.SystemParameters.PrimaryScreenWidth
System.Windows.SystemParameters.PrimaryScreenHeight
Это «Центр экрана DotNet 4.5 solution », используя SystemParameters вместо System.Windows.Forms или My. Compuer.Screen : Поскольку Windows 8 изменила расчет размера экрана , единственный способ, с которым он работает для меня, выглядит следующим образом:
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Dim BarWidth As Double = SystemParameters.VirtualScreenWidth - SystemParameters.WorkArea.Width
Dim BarHeight As Double = SystemParameters.VirtualScreenHeight - SystemParameters.WorkArea.Height
Me.Left = (SystemParameters.VirtualScreenWidth - Me.ActualWidth - BarWidth) / 2
Me.Top = (SystemParameters.VirtualScreenHeight - Me.ActualHeight - BarHeight) / 2
End Sub
[/g5]
в winforms C # У меня есть начальная точка (для случая, когда у нас есть несколько мониторов / diplay и одна форма вызывает другую) с помощью следующего метода:
private Point get_start_point()
{
return
new Point(Screen.GetBounds(parent_class_with_form.ActiveForm).X,
Screen.GetBounds(parent_class_with_form.ActiveForm).Y
);
}
Добавление решения, которое не использует WinForms, кроме NativeMethods. Сначала вам нужно определить собственные методы.
public static class NativeMethods
{
public const Int32 MONITOR_DEFAULTTOPRIMERTY = 0x00000001;
public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;
[DllImport( "user32.dll" )]
public static extern IntPtr MonitorFromWindow( IntPtr handle, Int32 flags );
[DllImport( "user32.dll" )]
public static extern Boolean GetMonitorInfo( IntPtr hMonitor, NativeMonitorInfo lpmi );
[Serializable, StructLayout( LayoutKind.Sequential )]
public struct NativeRectangle
{
public Int32 Left;
public Int32 Top;
public Int32 Right;
public Int32 Bottom;
public NativeRectangle( Int32 left, Int32 top, Int32 right, Int32 bottom )
{
this.Left = left;
this.Top = top;
this.Right = right;
this.Bottom = bottom;
}
}
[StructLayout( LayoutKind.Sequential, CharSet = CharSet.Auto )]
public sealed class NativeMonitorInfo
{
public Int32 Size = Marshal.SizeOf( typeof( NativeMonitorInfo ) );
public NativeRectangle Monitor;
public NativeRectangle Work;
public Int32 Flags;
}
}
И затем получите ручку монитора и информацию о мониторе, как это.
var hwnd = new WindowInteropHelper( this ).EnsureHandle();
var monitor = NativeMethods.MonitorFromWindow( hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST );
if ( monitor != IntPtr.Zero )
{
var monitorInfo = new NativeMonitorInfo();
NativeMethods.GetMonitorInfo( monitor, monitorInfo );
var left = monitorInfo.Monitor.Left;
var top = monitorInfo.Monitor.Top;
var width = ( monitorInfo.Monitor.Right - monitorInfo.Monitor.Left );
var height = ( monitorInfo.Monitor.Bottom - monitorInfo.Monitor.Top );
}
Я хотел иметь разрешение экрана, прежде чем открывать первый из моих окон, поэтому здесь можно быстро открыть невидимое окно перед фактическим измерением размеров экрана (вам нужно адаптировать параметры окна к окну, чтобы гарантировать, что оба являются открытыми на одном экране - в основном важно WindowStartupLocation
)
Window w = new Window();
w.ResizeMode = ResizeMode.NoResize;
w.WindowState = WindowState.Normal;
w.WindowStyle = WindowStyle.None;
w.Background = Brushes.Transparent;
w.Width = 0;
w.Height = 0;
w.AllowsTransparency = true;
w.IsHitTestVisible = false;
w.WindowStartupLocation = WindowStartupLocation.Manual;
w.Show();
Screen scr = Screen.FromHandle(new WindowInteropHelper(w).Handle);
w.Close();
Также вам может понадобиться:
, чтобы получить объединенный размер всех мониторов, а не в частности.
PresentationFramework.dll
и using System.Windows;
– Matt
4 May 2018 в 07:35
Мне нужно было установить максимальный размер моего окна приложения. Это может измениться, соответственно, приложение было показано на основном экране или во вторичном. Чтобы преодолеть эту проблему, e создал простой метод, который я покажу вам следующим образом:
/// <summary>
/// Set the max size of the application window taking into account the current monitor
/// </summary>
public static void SetMaxSizeWindow(ioConnect _receiver)
{
Point absoluteScreenPos = _receiver.PointToScreen(Mouse.GetPosition(_receiver));
if (System.Windows.SystemParameters.VirtualScreenLeft == System.Windows.SystemParameters.WorkArea.Left)
{
//Primary Monitor is on the Left
if (absoluteScreenPos.X <= System.Windows.SystemParameters.PrimaryScreenWidth)
{
//Primary monitor
_receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;
_receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;
}
else
{
//Secondary monitor
_receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;
_receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;
}
}
if (System.Windows.SystemParameters.VirtualScreenLeft < 0)
{
//Primary Monitor is on the Right
if (absoluteScreenPos.X > 0)
{
//Primary monitor
_receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.WorkArea.Width;
_receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.WorkArea.Height;
}
else
{
//Secondary monitor
_receiver.WindowApplication.MaxWidth = System.Windows.SystemParameters.VirtualScreenWidth - System.Windows.SystemParameters.WorkArea.Width;
_receiver.WindowApplication.MaxHeight = System.Windows.SystemParameters.VirtualScreenHeight;
}
}
}
window
на мониторе выше i> мой Первичный (например, егоTop < 0
), ,FromHandle
вернулScreen
для моего основного монитора (хотяwindow
был полностью i> в Secondary monitor)!?! Вздох. Похоже, мне придется самому искать массивScreen.AllScreens
. Почему нет вещей и просто работать??!? Arrrrgh. – Tom 28 April 2017 в 09:05