Anchor Window to Screen Edges in WPF

前端 未结 1 808
渐次进展
渐次进展 2021-01-06 12:32

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

1条回答
  •  有刺的猬
    2021-01-06 13:14

    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 讨论(0)
提交回复
热议问题