views:

152

answers:

2

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 base 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?

+2  A: 

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
}

}

Igor Zevaka
A: 

Found a solution by m1k4 on here:

http://stackoverflow.com/questions/1028024/snapping-sticky-wpf-windows

Kirk