开发者

Anchor Window to Screen Edges in WPF

I've decided to teach myself C# by writing a music player in Visual Studio 2010. I went with WPF because from what I hear it sounds like it will be a good ba开发者_StackOverflow社区se to skin from.

I want to program my window with the behavior where if the window comes to the edge of a screen (within 10px or so) it will snap to the screen edge. What's the best way to go about this?


Well there are a few areas you need to address. First to get notifications that the edge is coming close to the screen:

  1. Get notifications that window's size is changing. This one is easy - just use Window.SizeChanged event.
  2. Get notifications that window position is changing. This one is a bit tricky and I am not sure how to achieve it, might need to P/Invoke into Win32 API.

Then, there is a list of TODOs to work out if the window edge is close to the screen edge.

  1. Whether or not there are multiple monitors and if the window is solely contained within on monitor. This answer will help you get the monitor information.

  2. Handle the action of snapping the edge. Will need a bit of rect arithmetic acrobatics for this one. Then you either set Window.Top, Window.Left, Window.Height or Window.Width.

You will need conditional code for each edge but it will look something like this:

void SnapWindow(Window window, Size monitorSize) {
  if (window.Left < c_SnapThreshold && window.Left > 0)
    window.Left = 0;
  if (window.Left + window.Width > (monitorSize.Width - SnapThreshold) && window.Left + window.Width < monitorSize.Width)
    window.Width = monitorSize.Width - window.Left; //docks the right edge
  //..etc
}

}

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜