开发者

Constraining windows wpf

开发者 https://www.devze.com 2023-02-09 08:26 出处:网络
I have a window that needs to be constrained within another window. In order to do this, I hook into the SizeChanged event on the top level window....and in that event I need to adjust the second wind

I have a window that needs to be constrained within another window. In order to do this, I hook into the SizeChanged event on the top level window....and in that event I need to adjust the second window so that it is aligned to the nearest edge only if there is an intersection between the two i.e if the smaller window gets outside the boundary of the bigger window. I do a lot of math calculation to get this...and im still not near to the solution!

Im having trouble doing this because it involves a lot of messy code I was wondering if any of you guys had an easier solution to this?

Basically im dealing with 2 rectangles and I need to ensure that when the size of the bigger rectangle changes...if there is an intersection between the two, then the smaller rectangle should align itself to the edge of the bigger rectangle so that the smaller rectangle is开发者_如何学运维 within the bigger rectangle.

Could be a simple math problem in C# forms?

Any suggestions are welcome thanks!


For both windows you need to get the x and the y coordinates of the location of the window in systemcoordinates.

How to do this in wpf can be found here http://blogs.msdn.com/b/llobo/archive/2006/05/02/code-for-getting-screen-relative-position-in-wpf.aspx

Next you need to have the two windows react on each others sizechanged events so that the one window gets notified when the others size has changed.

Then the following math will do the job: (assuming window 1 is currently in the bounds of window 2 and window 2 size changes and you want to actually resize the window instead of moving it when possible)

//PSEUDOCODE
//Case1 (left bound changes)
if(window2.x > window1.x)
{
    window1.x = window2.x;
}
//Case2 (top bound changes)
if(window2.y > window1.y)
{
    window1.y = window2.y;
}
//Case3 (right bound changes)
if(window2.x + window2.width < window1.x + window1.width)
{
    window1.width = window2.x + window2.width - window1.x;
}
//Case4 (bottom bound changes)
if(window2.y + window2.height < window1.y + window1.height)
{
    window1.height = window2.y + window2.height - window1.y;
}        
0

精彩评论

暂无评论...
验证码 换一张
取 消