I am increasing the height of an NSWindow but if the window is positioned too far down the screen, the window increases in height and extends underneath the Dock. I want to prevent that from occurring.
When I researching this I stumbled upon this question which states the opposite problem - they said by default it will not extend underneath the Dock and they wanted it to. Perhaps this has changed in OS X Yosemite. In any case, I want to obtain either one of these two behaviors:
When the window is going to extend in height underneath the Dock,
resizing should stop and cause the window to sit flush with the Dock, so the window height is less than what was desired, or
resizing should continue, but resize from the top of the window instead of from the bottom, so it does not go underneath the Dock and is still the intended size
This is how the window resizing is triggered:
[self.window setFrame:windowFrame display:YES animate:YES];
This occurs in AppDelegate, and I have not overridden constrainFrameRect: toScreen:.
Also note this should also occur if their Dock is placed on the side and the window will go beyond the available screen space.
The area of the screen which is not occupied by the menu bar or the Dock is given by the visibleFrame property of NSScreen.
You maybe should override -constrainFrameRect:toScreen:. If not, you would adjust windowFrame before calling -setFrame:.... In the latter case, you can obtain the NSScreen from the window's screen property (assuming the frame you're assigning isn't moving it to a different screen).
You might use logic like this:
if (NSHeight(windowFrame) > NSHeight(screen.visibleFrame))
{
windowFrame.origin.y = NSMinY(screen.visibleFrame);
windowFrame.size.height = NSHeight(screen.visibleFrame);
}
else if (NSMinY(windowFrame) < NSMinY(screen.visibleFrame))
{
windowFrame.origin.y = NSMinY(screen.visibleFrame);
}
if (NSWidth(windowFrame) > NSWidth(screen.visibleFrame))
{
windowFrame.origin.x = NSMinX(screen.visibleFrame);
windowFrame.size.width = NSWidth(screen.visibleFrame);
}
else if (NSMinX(windowFrame) < NSMinX(screen.visibleFrame))
{
windowFrame.origin.x = NSMinX(screen.visibleFrame);
}
else if (NSMaxX(windowFrame) > NSMaxX(screen.visibleFrame))
{
windowFrame.origin.x = NSWidth(screen.visibleFrame) - NSWidth(windowFrame);
}
If you do override -constrainFrameRect:toScreen:, then you should call through to super. You can either do it after you've made your adjustments and let it constrain further, or call it first and then make your adjustments to what it returned.
Related
I have a UWP app. I want to be ale to create new windows from the app, but any subsequent window needs to be a specific smaller size compared to the main window. I don't do anything with regards to sizing the main window and let the OS take care of sizing it for me.
I bring up a new window like this:
auto window = CoreApplication::CreateNewView();
window->show();
void NewWindow::show() {
auto currView = ApplicationView::GetForCurrentView();
currView->PreferredLaunchViewSize =
Windows::Foundation::Size(float(options.width), float(options.height));
currView->PreferredLaunchWindowingMode = ApplicationViewWindowingMode::PreferredLaunchViewSize;
currView->SetPreferredMinSize(Size(20,20));
Xaml::Window::Current->Activate();
ApplicationViewSwitcher::TryShowAsStandaloneAsync(
window_->id(),
ViewSizePreference::Default,
window_->parentId(),
ViewSizePreference::Default);
}
When the main window comes up, it comes up just fine. When I click on a button which gets to this function, the new window comes up in the same size as the main window. I reopen the app, but now the main window shows up in the size I wanted the new window to show up in. Then clicking the button to bring up the new window brings up the new window in the size I wanted it in. So I am a bit confused. Am I setting the sizes the right way? Is there anything else glaringly wrong here?
As # Raymond Chen said, PreferredLaunchViewSize set the size when the app launches, it will change the size of your main window. And you can use ApplicationView.TryResizeView method to set the size of new window.
For example:
auto parentView = ApplicationView::GetForCurrentView();
auto newView = CoreApplication::CreateNewView();
newView->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this,parentView]()
{
int newViewId = 0;
Windows::UI::Xaml::Controls::Frame^ rootFrame = ref new Windows::UI::Xaml::Controls::Frame();
rootFrame->Navigate(Windows::UI::Xaml::Interop::TypeName(MainPage::typeid), nullptr);
Window::Current->Content = rootFrame;
// You have to activate the window in order to show it later.
Window::Current->Activate();
newViewId = ApplicationView::GetForCurrentView()->Id;
IAsyncOperation<bool>^ mytask = ApplicationViewSwitcher::TryShowAsStandaloneAsync(newViewId);
auto deviceEnumTask = concurrency::create_task(mytask);
deviceEnumTask.then([this](bool res)
{
// set the size of new window
ApplicationView::GetForCurrentView()->TryResizeView(Size(600, 320));
});
}));
I'm creating a small non-modal dialog in TornadoFX like this:
find<Grib>(scope).apply { openModal(block = true,
owner = FX.primaryStage,
stageStyle = StageStyle.UTILITY,
modality = Modality.NONE) }
How do I go about setting (and retrieving) it's window position for later? That is, I have a preferences object for the window location and I want to update it so that the next time the user opens the window, it opens in the same place they last closed it.
I was able to mostly solve my problem by digging through some of the TornadoFX source code.
I added this to my init{} function:
Platform.runLater {
root.scene.window.x = Main.preferences.getDouble(GRIB_WINDOW_X, 400.0)
root.scene.window.y = Main.preferences.getDouble(GRIB_WINDOW_Y, 400.0)
}
And then adding this to my close() function:
Main.preferences.putDouble(GRIB_WINDOW_X, root.scene.window.x)
Main.preferences.putDouble(GRIB_WINDOW_Y, root.scene.window.y)
This "mostly" solves the problem in that it does save/restore the window position, however the window flickers when it is created as it moves from some default position to the newly set position.
My app has a main window which creates and opens an instance of a subclass of a QML Window {} using createObject(). This window has its flags: set to be a borderless window (I've added code so that it can be grabbed and dragged around).
When I attach a monitor to my laptop and set its font scale factor to 125% (or 150%), when I drag my main window over to the second monitor, you can see it suddenly "snap" to the larger size when it reaches the halfway point. Likewise, when I drag it back to my laptop screen it again "snaps" to the smaller size when I get halfway over (this behavior is what I want, so no problems here).
My problem is that when I drag my created borderless window over into the monitor, it keeps the original 100% scale factor and does not "snap" to a larger size. If I drag my main window over to the monitor, it gets larger but the borderless window remains at the smaller scale; only when I grab the borderless window and move it slightly does it suddenly "snap" to the larger scale size. The same thing happens in reverse - if I then drag the borderless window back onto the laptop, it remains at the larger size until I drag the main window back over and then move the borderless window slightly (at which point it suddenly "snaps" to the smaller size).
So it appears that this created Window uses the scale factor of the screen that the parent window window that created it is currently in, even if it is in a different screen itself.
Is this happening because the Window is borderless? (I'm about to test this but my build process is incredibly slow) Or is there any way to set this borderless Window up so that it detects that it is crossing into a new screen and re-scales itself (in the same way that my main window does)?
Update: I just ran a test giving my Window a native titlebar, and with a titlebar the window instantly adopts ("snaps to") the scale factor of whichever screen it happens to be in, just like my main window (and independent of the main window's scale factor).
So is there any way to duplicate this auto-scaling window behavior with a borderless window? Some flag I need to call, or some method(s) I need to call to get the OS to rescale the window?
Update 2: I tried out Felix's SetWindowPos solution. It does move the window, but this does not fix the scaling problem - the behavior of the frameless window is the same and it still does not correctly pick up the scaling factor of the screen it is in.
I am running a test using MoveWindow instead of SetWindowPos to see if that affects anything [edit: MoveWindow does not work, either - same problem]. Then I'm going to try SendMessage or PostMessage along with NoBugz' suggestion of the WM_DPICHANGED message.
Any other suggestions are welcome.
Update 3: I just created a quick C# app (winforms) to see if the same problem occurs with that, and it doesn't - when a borderless form in the C# app is dragged over into the other monitor, it immediately picks up the scale factor change. So it appears this is a Qt problem.
Update 4: See my answer below for a working solution to this problem (if a bit of a hack).
So as far as I understand, your current goal is to move the window via the WIN-API.
You will have to do so via C++. The approach would be:
Pass the QML Window to a C++-Method exposed to QML as a QQuickWindow (The QML window instanciates that type, as seen in the documentation)
Use QWindow::winId to get the native HWND
Call the SetWindowPos WIN-API method to move it
Code sample (C++-part):
// the method
void moveWindow(QQuickWindow *window, int x, int y) {
HWND handle = (HWND)window->winId();
Q_ASSERT(handle);
::SetWindowPos(handle, HWND_TOP,
x, y, 0, 0,
SWP_NOSIZE | SWP_NOZORDER);
}
// assuming "moveWindow" is a member of "MyClass"
qmlEngine->rootContext()->setContextProperty("mover", new MyClass(qmlEngine));
Code sample (QML-part):
// call this method as soon as the drag has finished, with the new positions
mover.moveWindow(idOfWindow, xPos, yPos);
Note: I would recommend you try out calling this only after the drag was finished (and move the window as you do right now until then). If that works, you can try out what happens if you call this during the drag instead of changing the x/y of the window.
I figured out a relatively simple way to fix this problem. Since a frameless window in Qt gets its scaling factor from the window that created it, the trick is to create another window (that has a titlebar but is not visible to the user) and create the frameless window there, and then add code to the frameless window to keep the hidden window positioned underneath it as the user drags it. When the frameless window is dragged into another screen, the hidden window goes with it, picks up the new scale factor (since it has a titlebar) and then the frameless window immediately gets the new screen's scale factor as well.
Here is sample solution code:
// HiddenWindow.qml
Window {
id: hiddenWindow
// note: just making window visible: false does not work.
opacity: 0
visible: true
flags: Qt.Tool | Qt.WindowTitleHint | Qt.WindowTransparentForInput |
Qt.WindowStaysOnTopHint // Qt.Tool keeps this window out of the
// taskbar
function createVisibleWindow() {
var component = Qt.createComponent("VisibleWindow.qml")
if (component.status === Component.Ready) {
var win = component.createObject(hiddenWindow)
return win
}
}
}
// VisibleWindow.qml
Window {
id: visibleWindow
property var creatorWindow: undefined
flags: Qt.FramelessWindowHint
onXChanged: {
creatorWindow.x = x
}
onYChanged: {
creatorWindow.y = y
}
onWidthChanged: {
creatorWindow.width = width
}
onHeightChanged: {
creatorWindow.height = height
}
}
And then to use these classes from your main window QML:
property var hiddenWindow: undefined
property var visibleWindow: undefined
Component.onCompleted: {
var component = Qt.createComponent("HiddenWindow.qml")
if (component.status === Component.Ready) {
hiddenWindow = component.createObject(null)
}
visibleWindow = hiddenWindow.createVisibleWindow()
visibleWindow.creatorWindow = hiddenWindow
visibleWindow.show()
}
You need to resize window when window move to other screen
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton
onPressed: {
movePos = Qt.point(mouse.x, mouse.y)
isDoubleClicked = false
lastWindowWidth = mainWindow.width
lastWindowHeight = mainWindow.height
}
onPositionChanged: {
if (!isDoubleClicked) {
const delta = Qt.point(mouse.x - movePos.x, mouse.y - movePos.y)
if (mainWindow.visibility !== Window.Maximized) {
mainWindow.x = mainWindow.x + delta.x
mainWindow.y = mainWindow.y + delta.y
mainWindow.width = lastWindowWidth
mainWindow.height = lastWindowHeight
}
}
}
}
Could anyone point me to (or provide?) some nice, clear examples of how to implement scrolling in Win32? Google brings up a lot of stuff, obviously, but most examples seem either too simple or too complicated for me to be sure that they demonstrate the right way of doing things. I use LispWorks CAPI (cross-platform Common Lisp GUI lib) in my current project, and on Windows I have a hard-to-figure-out bug relating to scrolling; basically I want to do some tests directly via the Win32 API to see if I can shed some light on the situation.
Many thanks,
Christopher
I think you are talking for an example how to handle WM_VSCROLL/WM_HSCROLL event. If so first step is to handle that event. You shouldn't use the HIWORD(wParam) value of that call but use GetScrollInfo, GetScrollPos, and GetScrollRange functions instead.
Following is an example code snipped by MSDN - Using Scroll Bars. xCurrentScroll is determined before by calling GetScrollPos() for example.
int xDelta; // xDelta = new_pos - current_pos
int xNewPos; // new position
int yDelta = 0;
switch (LOWORD(wParam)) {
// User clicked the scroll bar shaft left of the scroll box.
case SB_PAGEUP:
xNewPos = xCurrentScroll - 50;
break;
// User clicked the scroll bar shaft right of the scroll box.
case SB_PAGEDOWN:
xNewPos = xCurrentScroll + 50;
break;
// User clicked the left arrow.
case SB_LINEUP:
xNewPos = xCurrentScroll - 5;
break;
// User clicked the right arrow.
case SB_LINEDOWN:
xNewPos = xCurrentScroll + 5;
break;
// User dragged the scroll box.
case SB_THUMBPOSITION:
xNewPos = HIWORD(wParam);
break;
default:
xNewPos = xCurrentScroll;
}
[...]
// New position must be between 0 and the screen width.
xNewPos = max(0, xNewPos);
xNewPos = min(xMaxScroll, xNewPos);
[...]
// Reset the scroll bar.
si.cbSize = sizeof(si);
si.fMask = SIF_POS;
si.nPos = xCurrentScroll;
SetScrollInfo(hwnd, SB_HORZ, &si, TRUE);
Here's one, ScrollCall, (copy from page):.
ScrollCall is a demo program that takes a sample of Windows standard
controls, along with a standard GDI image, and arranges them on a
Device Context (or DC), in a window. Depending on the dimensions of
the image, and the size of the containing window, horizontal and/or
system scrollbars become visible, to enable scrolling for the image
and controls. Thus ScrollCall is as at least as much focused on sizing
as it is scrolling, and both offer unique challenges for the
programmer.
ScrollCall features:
System scroll bars
Optional groupbox
Button to open images on the Device Context (DC)
Radio options for choice of window scroll function
Checkbox to stretch rather than scroll the image
Label Paint Mult with UpDown and Buddy to increase the wait times of WM_SIZE during sizing, thus reduced WM_PAINT processing
Right click for system snapshot of view in default or monitor attached to desktop
Double-click to print the visible part of the (mostly empty) client window to the DC, and back to the client window (experimental)
ScrollCall temporarily turns on SPI_SETDRAGFULLWINDOWS for the testing of the visual effects of dragging, if ever it was toggled off
Compatibility with AeroSnap sizing
I noticed that in Windows, if you maximize a window you can not resize it until you un-maximized it again. This appears to be a normal behaviour, so I would like to remove my resize gripper when the window is maximised.
At the moment I can't find a property to detect if a window is maximized, and although I could add a boolean in my controller, it wouldn't necessarily catch requests to maximize from the OS.
So if you know of a reliable way to test if a window is maximized please let me know.
On a related note, I am using custom chrome, and when I maximize a window it overlaps the windows task bar. I can think of hacks to detect available screen size (using a transparent system chrome window), but it would be good to know of a better method.
Thanks
Rob
In your application (MXML) on the in the init method you ussually call on creationComplete:
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
creationComplete="init()" >
Add the following code:
this.addEventListener(NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, trackState);
the method looks like this:
public function trackState(event:NativeWindowDisplayStateEvent):void
{
if (event.afterDisplayState == NativeWindowDisplayState.MAXIMIZED)
{
isMaximised = true;
} else {
isMaximised = false;
}
}
I have figured out how this can best be done thanks to some pointers from TheBrain.
Firstly you need to watch for resize events to the window your want to control:
NativeApplication.nativeApplication.activeWindow.addEventListener(NativeWindowBoundsEvent.RESIZE, onWindowResize);
Then handle that event to decide if the window is maximised or not:
public function onWindowResize(event:NativeWindowBoundsEvent):void
{
if (event.afterBounds.height >= Screen.mainScreen.visibleBounds.height && event.afterBounds.width >= Screen.mainScreen.visibleBounds.width)
isMaximised = true;
else
isMaximised = false;
}
You then need to catch or create your own maximize button, and when clicked perform the following code:
if (isMaximised)
{
var bounds:Rectangle = Screen.mainScreen.visibleBounds;
NativeApplication.nativeApplication.activeWindow.bounds = bounds;
}
else
{
NativeApplication.nativeApplication.activeWindow.bounds = new Rectangle(100, 100, 500, 600);
}
You can modify the bounds to over maximize (which is handy for custom chrome windows with shadows), and you can also set the application to reset to a default size if the maximize button is clicked when it's already maximized (or do nothing).
I had issues about when to assign the window resize listner, and ended up removing and adding it every time the maximize button was clicked. It's a bit of overkill, but not too bad.
There is Win32 API Call that will do this for you:
BOOL IsZoomed( HWND hWnd );
to get the actual usable space from the screen, use the flash.display.Screen class, or you can use the systemMaxSize() which returns the largest window size allowed by the OS. For maximization you have some events that the window is dispaching when maximized/minimized/restored. You can find more info on the adobe pages (the link under systemMaxSize).
To detect if window is maximized...I don't think there is such a function (I might be wrong) but you can test if the app size is equal with the available screen size which means it's maximized. Or hook on the resize event which is triggered when the app is maximized/minimized/resized
Here is an easier way of checking if a window is maximized:
if(stage.nativeWindow.displayState == NativeWindowDisplayState.MAXIMIZED)
{
//do something
}
The following worked for me. No need to set event listeners, this code can be used to check the real-time state of the native window:
if (nativeWindow.displayState == 'maximized')
{
trace('Maximized');
}
else
{
trace('Minimized');
}
Can you use something like this to hook the maximize() event?