我面临以下问题: 在WPF中,我有一个带有WindowStyle =“ None”的窗口,因此我添加了一个按钮,以使用DragMove()方法移动窗口。这部分工作正常。我还想要的是,当窗口到达某个位置时,它将停止DragMove。 我的想法是通过引发MouseLeftButtonLeft来实现这一点,认为它会中断DragMove,但不会。
移动窗口的按钮:
<Button Grid.Column="0" x:Name="MoveButton" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="3" Cursor="Hand">
<Image x:Name="MoveImage" Source="images/move.png" MouseLeftButtonDown="MoveWindow" MouseLeftButtonUp="Poney" />
</Button>
移动窗口的方法:
// Move the window with drag of the button. Ensure that we are not over the taskbar
private void MoveWindow(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
DragMove();
// https://stackoverflow.com/questions/48399180/wpf-current-screen-dimensions
System.Drawing.Rectangle workingArea = Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle).WorkingArea;
//The left property of the window is calculated on the width of all screens, so use VirtualScreenWidth to have the correct width
if (Top > (workingArea.Height - Height))
{
Top = (workingArea.Height - Height);
}
else if (Left > (SystemParameters.VirtualScreenWidth - Width))
{
Left = (SystemParameters.VirtualScreenWidth - Width);
}
else if (Left < 0)
{
Left = 0;
}
}
引发事件的方法:
private void MainWindow_LocationChanged(object sender, EventArgs e)
{
// https://stackoverflow.com/questions/48399180/wpf-current-screen-dimensions
System.Drawing.Rectangle workingArea = Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle).WorkingArea;
if(Left > 2000)
{
MouseButtonEventArgs mouseButtonEvent = new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Left)
{
RoutedEvent = MouseLeftButtonUpEvent,
Source = MoveImage
};
MoveImage.RaiseEvent(mouseButtonEvent);
//InputManager.Current.ProcessInput(mouseButtonEvent);
}
}
检查事件是否引发:
public void Poney(object sender, MouseButtonEventArgs e)
{
Console.WriteLine("Poney");
}
我在控制台上显示了“ poney”,所以我猜想引发该事件的代码在起作用吗?
简而言之,我需要一种方法来中断Dragmove,以便进行一些更改并重新启动DragMove。
谢谢:)
PS:2000值用于测试,以“真实”位置计算。
答案 0 :(得分:1)
您可以使用本机mouse_event函数来合成鼠标向上事件,例如:
const int MOUSEEVENTF_LEFTUP = 0x04;
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo);
void MainWindow_LocationChanged(object sender, EventArgs e)
{
if (Left > 1000)
{
Point point = Mouse.GetPosition(this);
mouse_event(MOUSEEVENTF_LEFTUP, (uint)point.X, (uint)point.Y, 0, 0);
}
}