Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CenterOnScreen has window visibility change side-effect #132

Closed
riverar opened this issue Sep 12, 2023 · 1 comment
Closed

CenterOnScreen has window visibility change side-effect #132

riverar opened this issue Sep 12, 2023 · 1 comment

Comments

@riverar
Copy link

riverar commented Sep 12, 2023

Wasn't expecting CenterOnScreen to make my window visible (usage of SWP_SHOWWINDOW parameter). Would recommend removing this and keeping window visibility state changes separate.

public static void CenterOnScreen(IntPtr hwnd, double? width = null, double? height = null)
{
var hwndDesktop = PInvoke.MonitorFromWindow(new(hwnd), MONITOR_FROM_FLAGS.MONITOR_DEFAULTTONEAREST);
MONITORINFO info = new MONITORINFO();
info.cbSize = 40;
PInvoke.GetMonitorInfo(hwndDesktop, ref info);
var dpi = PInvoke.GetDpiForWindow(new HWND(hwnd));
PInvoke.GetWindowRect(new HWND(hwnd), out RECT windowRect);
var scalingFactor = dpi / 96d;
var w = width.HasValue ? (int)(width * scalingFactor) : windowRect.right - windowRect.left;
var h = height.HasValue ? (int)(height * scalingFactor) : windowRect.bottom - windowRect.top;
var cx = (info.rcMonitor.left + info.rcMonitor.right) / 2;
var cy = (info.rcMonitor.bottom + info.rcMonitor.top) / 2;
var left = cx - (w / 2);
var top = cy - (h / 2);
SetWindowPosOrThrow(new HWND(hwnd), new HWND(), left, top, w, h, SET_WINDOW_POS_FLAGS.SWP_SHOWWINDOW);
}

@riverar
Copy link
Author

riverar commented Sep 12, 2023

Nice like rice, thanks @dotMorten

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant