我的Window
元素有WindowStyle="None"
和AllowsTransparency="True"
,因此它没有标题栏并且支持透明度。
我希望用户能够通过左键单击窗口中的任意位置并拖动来将窗口移动到屏幕上的任何位置。只要按下鼠标左键,窗口就会随鼠标一起拖动。
我能够使用这个功能有一个例外:当鼠标移动到窗口之外时(例如当在窗口边缘按下鼠标左键并且鼠标移动时),窗口不再捕获鼠标位置,也不会随鼠标一起拖动。
以下是我用来完成工作的代码隐藏代码:
public Point MouseDownPosition { get; set; }
public Point MousePosition { get; set; }
public bool MouseIsDown { get; set; }
private void window_MyWindowName_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
MouseDownPosition = e.GetPosition(null);
MouseIsDown = true;
}
private void window_MyWindowName_MouseMove(object sender, MouseEventArgs e)
{
if (MouseIsDown)
{
MousePosition = e.GetPosition(null);
Left += MousePosition.X - MouseDownPosition.X;
Top += MousePosition.Y - MouseDownPosition.Y;
}
}
private void window_MyWindowName_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
MouseIsDown = false;
}
答案 0 :(得分:9)
我认为你正在寻找这个:用C#处理全球鼠标和键盘钩子
网址:Processing Global Mouse and Keyboard Hooks in C#
即使应用程序在后台运行或根本没有任何用户界面,此类允许您点击键盘和鼠标和/或检测其活动。
此类使用KeyEventArgs和MouseEventArgs引发常见的.NET事件,因此您可以轻松检索所需的任何信息。
有一个例子,解释和演示可供使用。
很棒的教程!
示例:
UserActivityHook actHook;
void MainFormLoad(object sender, System.EventArgs e)
{
actHook= new UserActivityHook(); // crate an instance
// hang on events
actHook.OnMouseActivity+=new MouseEventHandler(MouseMoved);
actHook.KeyDown+=new KeyEventHandler(MyKeyDown);
actHook.KeyPress+=new KeyPressEventHandler(MyKeyPress);
actHook.KeyUp+=new KeyEventHandler(MyKeyUp);
}
现在,举例说明如何处理事件:
public void MouseMoved(object sender, MouseEventArgs e)
{
labelMousePosition.Text=String.Format("x={0} y={1}", e.X, e.Y);
if (e.Clicks>0) LogWrite("MouseButton - " + e.Button.ToString());
}
答案 1 :(得分:6)
我相信你正在重新发明轮子。搜索“Window.DragMove”。
示例:
private void title_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.DragMove();
}
答案 2 :(得分:0)
以这种方式尝试:
// method to convert from 'old' WinForms Point to 'new' WPF Point structure:
public System.Windows.Point ConvertToPoint(System.Drawing.Point p)
{
return new System.Windows.Point(p.X,p.Y);
}
// some locals you will need:
bool mid = false; // Mouse Is Down
int x=0, y=0;
// Mouse down event
private void MainForm_MouseDown(object sender, MouseButtonEventArgs e)
{
mid=true;
Point p = e.GetPosition(this);
x = (int)p.X;
y = (int)p.Y;
}
// Mouse move event
private void MainForm_MouseMove(object sender, MouseButtonEventArgs e)
{
if(mid)
{
int x1 = e.GetPosition(this).X;
int y1 = e.GetPosition(this).Y;
Left = x1-x;
Top = y1-y;
}
}
// Mouse up event
private void MainForm_MouseUp(object sender, MouseButtonEventArgs e)
{
mid = false;
}