前言
wpf中的WebBrowser相比之前的winform阉割了不少东西,也增加了不少东西,但是msdn对wpf也没有较好的文档
WebBrowser可以说是一个.NET控件,相对于WPF中的控件,不在同一线程,它们不可重叠,相当于两个独立的窗口(window)
正题
如上图所示,使用前端技术来实现的页面,因为要用到轮播,才用的webBrowser,wpf做这些很麻烦,但是无边框窗体,如果我们要拖动窗口,如果是wpf原生控件的话,很简单,给控件添加事件,然后
private void window_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
try
{
this.DragMove();
}
catch { }
}
}
但是如果想要通过拖动WebBrowser来移动窗口这样是不行,我们需要通过js的拖拽事件响应到C#端进行窗口定位
js拖拽代码
var Drag = function () {
var drag = function (e) {
e = e || window.event;
window.external.Drag();
}
var dragend = function () {
document.onmouseup = null;
document.onmousemove = null;
window.external.DragEnd();
}
var dragstart = function (e) {
e = e || window.event;
document.onmouseup = dragend;
document.onmousemove = drag;
window.external.DragStart();
return false;
}
document.onmousedown = dragstart;
}
C#端只需要接收到动作然后根据鼠标位置设置窗口的position即可
public void DragStart()
{
POINT p = new POINT();
GetCursorPos(out p);
this.offset.X = p.X - instance.Left;
this.offset.Y = p.Y - instance.Top;
}
public void Drag()
{
POINT p = new POINT();
GetCursorPos(out p);
instance.Left = p.X - this.offset.X;
instance.Top = p.Y - this.offset.Y;
}
public void DragEnd()
{
this.offset.X = 0;
this.offset.Y = 0;
}
这里的POINT是使用了结构体
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
public POINT(int x, int y)
{
this.X = x;
this.Y = y;
}
public override string ToString()
{
return ("X:" + X + ", Y:" + Y);
}
}
GetCursorPos 是调用了user32.dll的GetCursorPos来获取鼠标位置
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT pt);
具体这些算的,就比较简单了,跟js的拖拽元素的原理一样的