C# 控件.PointToScreen 遇到的问题
先上一点代码。
//Btn 是已知的button Point pt = Btn.PointToScreen(new System.Windows.Point(0, 0)); MessageBox.Show("Button " + pt.X.ToString() + " " + pt.Y.ToString());
代码运行到这里的时候就会弹出一个消息框显示 Btn 左上角坐标。
当程序最小化时,却出现了。
由于具体原因未知,暂添加代码判断该坐标位于屏幕内(width: 0 ~ height - 1, height : 0 ~ height - 1)
Point pt = RunBtn.PointToScreen(new System.Windows.Point(0, 0)); if (pt.X >= 0 && pt.Y >= 0 && pt.X <= SystemParameters.PrimaryScreenWidth && pt.Y <= SystemParameters.PrimaryScreenHeight) { MessageBox.Show("Button " + pt.X.ToString() + " " + pt.Y.ToString()); }
**********20220701更新**********
以上内容因为一些操作出现“此 Visual 未连接到 PresentationSource”
if (RunBtn.IsVisible) { Point pt = RunBtn.PointToScreen(new System.Windows.Point(0, 0)); }
建议阅读 https://stackoverflow.com/questions/24802945/find-location-of-a-control-in-wpf-using-pointtoscreen
另外,以上代码运行在多个屏幕的PC时坐标可能确实为负数,具体需要接触多屏幕的东西,暂不了解。
// 多屏幕 System.Drawing.Rectangle rect = new System.Drawing.Rectangle(); if (System.Windows.Forms.Screen.AllScreens.Length > 1) { // 所有屏幕 rect = System.Windows.Forms.SystemInformation.VirtualScreen; // 首个屏幕 rect = System.Windows.Forms.Screen.AllScreens[0].Bounds; } else { // 单屏幕 rect = System.Windows.Forms.SystemInformation.VirtualScreen; }