簡體   English   中英

在 wpf 中移動無邊框 window

[英]Move a borderless window in wpf

在我的 C# WinForms 應用程序中,我有一個主 window 隱藏了默認控件。

所以為了讓我可以移動它,我在主 window 中添加了以下內容:

private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;
private const int WM_NCLBUTTONDBLCLK = 0x00A3;

protected override void WndProc(ref Message message)
{
    if (message.Msg == WM_NCLBUTTONDBLCLK)
    {
        message.Result = IntPtr.Zero;
        return;
    }

    base.WndProc(ref message);

    //Allow window to move
    if (message.Msg == WM_NCHITTEST && (int)message.Result == HTCLIENT)
        message.Result = (IntPtr)HTCAPTION;
}

我有一個 WPF 應用程序,我還隱藏了默認控件,我也想做同樣的事情。 我看到主要的 window 是從“窗口”派生的,所以上面的代碼不起作用。 如何在 WPF 中執行此操作?

為此,您需要將事件處理程序附加到窗口的MouseDown事件,檢查是否按下了鼠標左鍵並在窗口上調用DragMove方法。

以下是具有此功能的窗口示例:

public partial class MyWindow : Window
{
    public MyWindow()
    {
        InitializeComponent();
        MouseDown += Window_MouseDown;
    }

    private void Window_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.ChangedButton == MouseButton.Left)
            DragMove();
    }
}

正如我在你的另一個主題中所說,在我在WPF中創建自定義窗口的過程中,我發現了一些在線處理Win32 API以Resize窗口Resize的方法,如果你想拖動窗口,JustinM代碼是正確的。

代碼有點廣泛。 它處理游標,消息到WndProc和所有。 我將留下解釋它的鏈接。

WPF無邊框窗口調整大小

超級簡單,在這里:

private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
    DragMove();
}

首先,您需要確保用戶想要拖動 window。 所以鼠標的左鍵應該向下並且它應該移動至少一些像素。 創建一個點屬性來存儲光標的精確點,並向 window 本身添加兩個事件:PreviewMouseLeftButtonDown 和 MouseMove。 檢查下面的代碼。

private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
  Position = e.GetPosition(null);
}



private void Window_MouseMove(object sender, MouseEventArgs e)
    {

        Point mousePos = e.GetPosition(null);
        Vector diff = Position - mousePos;

        if (e.LeftButton == MouseButtonState.Pressed &&
            (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
            Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
        {
            DragMove();
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM