簡體   English   中英

在WPF中將窗口位置設置為跟隨光標的問題

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

我正在嘗試在WPF中執行拖放操作。 我清楚地記得我經常做這種事情的日子。

我正在使用ap /調用GetCursorPos()返回屏幕坐標。 該數字與光標的偏移量很大。

我認為這個問題是縮放由於我的筆記本電腦的高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;          
}

盡管從p /調用中獲得的dpi值是正確的,但結果卻相距遙遠(比使用原始GetCursorPos()值差得多)。

因此,在嘗試了所有可以找到的所有不同選項之后,我對如何在Window上獲取正確的值感到困惑。

我可以通過以下方法使其起作用,但是我希望有人可以提供一個很好的解釋:

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