我正在 c# 上编写一个实现鼠标和键盘钩子的程序,一旦单击指定的键,它将去抓取前景窗口并将其 x、y、高度和宽度保存到 xml 文件中。
我不确定出了什么问题,但我不断收到错误的尺寸和错误的参数。
我很感激这方面的帮助,因为我现在已经为此苦苦挣扎了两天。
波纹管是相关代码。
标准声明:
//rectangle for the windows size
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
//win API
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern bool SetForegroundWindow(IntPtr hwnd);
[DllImport("user32.dll", SetLastError = true)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT Rect);
以及相关代码本身
void mouseHook_MouseDown(object sender, MouseEventArgs e)
{
this.handle = GetForegroundWindow();
}
#region keyboard pressed
void keyboardHook_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F9) //if slot selected
{
RECT Rect = new RECT();
SetForegroundWindow(this.handle);
//this.handle = GetForegroundWindow();
GetWindowRect(this.handle, ref Rect);
Grid newSlot = new Grid();
newSlot.topX = Rect.Top;
newSlot.topY = Rect.Left;
newSlot.width = Rect.Right - Rect.Left;
newSlot.height = Rect.Bottom - Rect.Top;
layoutGrid.Add(newSlot);
lbl_slots.Text = layoutGrid.Count().ToString();
}
else if (e.KeyCode == Keys.F10) //if main stack slot selected
{
RECT Rect = new RECT();
SetForegroundWindow(handle);
GetWindowRect(GetForegroundWindow(), ref Rect);
for (int i = 0; i < layoutGrid.Count(); i++) //selecting slot for main stack
{
layoutGrid[i].slot_number = i + 1; //setting slots numbers
if (layoutGrid[i].topX != Rect.Top && layoutGrid[i].topY != Rect.Left)
layoutGrid[i].is_stack = false;
else
{
layoutGrid[i].is_stack = true;
lbl_stackSlot.Text = (i + 1).ToString();
}
}
}
}
编辑: 我尝试同时使用公共结构 RECT 和 Rectangle,我收到的 RECT 值似乎是随机的,我的意思是 left 和 top 以及 height 和 width,有时它会找到合适的点,但有时它似乎完全是随机的. 我用 Rectangle 收到的值似乎有正确的 left 和 top 但返回错误的高度和宽度。