功能:拖动无标题窗口
环境:vs2010,wpf
方法1:
前台代码:
<Window x:Class="DragWnd.DragWnd"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="120" Width="280" WindowStyle="None" ResizeMode="NoResize" Background="#FFB3E8B3" MouseLeftButtonDown="Window_MouseLeftButtonDown">
<Grid>
<Label Content="按下鼠标左键拖拽" Height="23" HorizontalAlignment="Left" Margin="44,30,0,0" Name="label1" VerticalAlignment="Top" Width="144" />
</Grid>
</Window>
后台代码:
using System;using System.Windows;
using System.Windows.Input;
using System.Runtime.InteropServices;
namespace DragWnd
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class DragWnd : Window
{
public DragWnd()
{
InitializeComponent();
}
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
public const int WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 0xF010;
public const int HTCAPTION = 0x0002;
Point pos = new Point();
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
pos = e.GetPosition(null);
IntPtr hWnd = GetForegroundWindow();
SendMessage(hWnd, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}
}
}
方法2:
添加事件:MouseDown 或 MouseLeftButtonDown
/// <summary>
/// 点击按钮 拖动窗口
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void radBtn_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
DragMove();
}
}