First, introduce PInvoke.net or Microsoft.Windows.CsWin32, refer to:
https://www.whuanle.cn/archives/21436
Define two functions to get the screen dimensions without the taskbar:
public static int GetSystemMetrics_SM_CYMAXIMIZED()
{
return PInvoke.GetSystemMetrics(Windows.Win32.UI.WindowsAndMessaging.SYSTEM_METRICS_INDEX.SM_CYMAXIMIZED);
}
public static int GetSystemMetrics_SM_CXFULLSCREENY()
{
return PInvoke.GetSystemMetrics(Windows.Win32.UI.WindowsAndMessaging.SYSTEM_METRICS_INDEX.SM_CXMAXIMIZED);
}
Then, write code to call these functions after InitializeComponent()
in the window's constructor.
The first step is to calculate the initial size of the window at startup. The default setting is 0.7 * 0.8
of the screen size.
The second step is to set the SizeChanged event to get the height or width of the screen without the taskbar. Since some users may have the taskbar on the left or right side, both height and width need extra calculation.
The third step notes two points regarding multiple screens that a computer may have:
- When the user drags the window, the window should not be allowed to be dragged to the edge; otherwise, it may disappear off the screen or become too small to drag back from the edge.
- The second point is that since there may be multiple screens with different sizes, calculations need to be made after dragging the window.
var nativeWindow = this;
// Working area size
var PX = SystemParameters.FullPrimaryScreenWidth;
var PY = SystemParameters.FullPrimaryScreenHeight;
nativeWindow.Width = PX * 0.7;
nativeWindow.Height = PY * 0.8;
nativeWindow.MinHeight = 400;
nativeWindow.MinWidth = 500;
nativeWindow.MaxHeight = GetSystemMetrics_SM_CXFULLSCREENY();
nativeWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
nativeWindow.SizeChanged += (sender, e) =>
{
if (nativeWindow.WindowState == WindowState.Maximized)
{
return;
}
};
nativeWindow.LocationChanged += (sender, e) =>
{
Window window = (Window)sender!;
// Current screen range
var x = GetSystemMetrics_SM_CYMAXIMIZED();
var y = GetSystemMetrics_SM_CXFULLSCREENY();
var (sizeHeight, sizeWidth) = (window.Height, window.Width);
var (positionX, positionY) = (window.Left, window.Top);
var _x = positionX;
var _y = positionY;
if (positionY < 0)
y = 0;
else if (y - positionY < 100)
_y = y - 100;
if (_x != positionX || _y != positionY)
{
window.Left = _x;
window.Top = _y;
}
};
文章评论