我自己解決了這個問題,出現了一些有趣的計算,為我工作,為任何窗口( 任何活動前景窗口) 工作。 如果你在評論后按下滑鼠,你就可以在活動窗口中按下滑鼠右鍵,這樣就不會需要滑鼠點擊或者任何滑鼠點擊。public void MoveWindow_AfterMouse()
{
//1- get a handle to the foreground window (or any window that you want to move).
//2- set the mouse pos to the window's center.
//3- let the window move with the mouse in a loop, such that:
//win(x) = mouse(x) - win(width)/2
//win(y) = mouse(y) - win(height)/2
//This is because the origin (point of rendering) of the window, is at its top-left corner and NOT its center!
//1-
IntPtr hWnd = WinAPIs.GetForegroundWindow();
//2- Then:
//first we need to get the x, y to the center of the window.
//to do this, we have to know the width/height of the window.
//to do this, we could use GetWindowRect which will give us the coords of the bottom right and upper left corners of the window,
//with some math, we could deduce the width/height of the window.
//after we do that, we simply set the x, y coords of the mouse to that center.
RECT wndRect = new RECT();
WinAPIs.GetWindowRect(hWnd, out wndRect);
int wndWidth = wndRect.right - wndRect.left;
int wndHeight = wndRect.bottom - wndRect.top;//cuz the more you go down, the more y value increases.
Point wndCenter = new Point(wndWidth/2, wndHeight/2);//this is the center of the window relative to itself.
WinAPIs.ClientToScreen(hWnd, out wndCenter);//this will make its center relative to the screen coords.
WinAPIs.SetCursorPos(wndCenter.X, wndCenter.Y);
//3- Moving :)))
while (true)
{
Point cursorPos = new Point();
WinAPIs.GetCursorPos(out cursorPos);
int xOffset = cursorPos.X - wndWidth/2;
int yOffset = cursorPos.Y - wndHeight/2;
WinAPIs.MoveWindow(hWnd, xOffset, yOffset, wndWidth, wndHeight, true);
Thread.Sleep(25);
}
}
現在:int moveCommandToggle = 0;
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0312)
{
int keyID = m.WParam.ToInt32();
if(keyID == some_key_combo_you_registered_for_the_moving)
{
if (moveCommandToggle++ % 2 == 0)
{
mover = new Thread(() => MoveWindow_AfterMouse());
mover.Start();
}
else mover.Abort();
}
}
}
如果你想了解 RECT:public struct RECT
{
public int left;//xCoor of upper left corner.
public int top;//yCoor of upper left corner.
public int right;//xCoor of lower right corner.
public int bottom;//yCoor of lower right corner.
};
WinAPIs只是一個 static 類,我在其中做了 DllImports 。