简体   繁体   English

在WPF中将窗口位置设置为跟随光标的问题

[英]Problems with setting Window postion to follow cursor in WPF

I'm attempting to perform a drag and drop operation in WPF. 我正在尝试在WPF中执行拖放操作。 I distinctly remember the days when I did this sort of thing regularly. 我清楚地记得我经常做这种事情的日子。

I'm using ap/invoke of GetCursorPos() to return screen coordinates. 我正在使用ap /调用GetCursorPos()返回屏幕坐标。 This number is offset from the cursor by quite a bit. 该数字与光标的偏移量很大。

I assumed the issue was scaling due to my laptop's high-DPI setting (120) so I used the following code (stolen from this answer): 我认为这个问题是缩放由于我的笔记本电脑的高DPI设置(120),所以我用下面的代码(从偷来的这个答案):

private Point ConvertPixelsToUnits(int x, int y)
{
// get the system DPI
IntPtr dDC = GetDC(IntPtr.Zero); // Get desktop DC
int dpi = GetDeviceCaps(dDC, 88);
bool rv = ReleaseDC(IntPtr.Zero, dDC);

// WPF's physical unit size is calculated by taking the 
// "Device-Independant Unit Size" (always 1/96)
// and scaling it by the system DPI
double physicalUnitSize = (1d / 96d) * (double)dpi;
Point wpfUnits = new Point(physicalUnitSize * (double)x,
    physicalUnitSize * (double)y);

return wpfUnits;          
}

While the dpi value is correct from the p/invokes,, the result is way, way off (significantly worse than using the raw GetCursorPos() value). 尽管从p /调用中获得的dpi值是正确的,但结果却相距遥远(比使用原始GetCursorPos()值差得多)。

So after lots of playing around with all the different options I can find, I am at a loss as to how to get the correct values on the Window. 因此,在尝试了所有可以找到的所有不同选项之后,我对如何在Window上获取正确的值感到困惑。

I can make it work with the following, but I'm hoping someone can provide a good explanation: 我可以通过以下方法使其起作用,但是我希望有人可以提供一个很好的解释:

var transform = PresentationSource.FromVisual(PacksApp.Current.MainWindow).CompositionTarget.TransformFromDevice;
var pointOfMouse = transform.Transform(GetCursorPos());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM