我正在使用c#应用程序,该应用程序使用全局c#鼠标和键盘钩子捕获系统事件,但是在输入时我无法获得当前键盘光标位置值。
以下是我的代码,它总是将GetCaretPos输出返回为(0,0)
PointDetail curPoint = new PointDetail();
Point position = new Point();
IntPtr hwndFoc;
IntPtr hwndFG = WinApiDelegate.GetForegroundWindow();
uint processID = 0;
uint mainWindowProcessId = 0;
IntPtr activeWindowThreadProcess = WinApiDelegate.GetWindowThreadProcessId(hwndFG, IntPtr.Zero);
IntPtr currWindowThread = IntPtr.Zero;
int thisWindowThread = 0;
this.Invoke(new MethodInvoker(delegate
{
currWindowThread = WinApiDelegate.GetWindowThreadProcessId(this.Handle, IntPtr.Zero);
thisWindowThread = WinApiDelegate.GetWindowThreadProcessId(this.Handle, out mainWindowProcessId);
}));
int activeWindowThread = WinApiDelegate.GetWindowThreadProcessId(hwndFG, out processID);
if (activeWindowThread != Thread.CurrentThread.ManagedThreadId)
{
WinApiDelegate.AttachThreadInput(activeWindowThreadProcess, currWindowThread, true);
hwndFoc = WinApiDelegate.GetActiveWindow();
bool CaretPos = WinApiDelegate.GetCaretPos(ref position);
}
答案 0 :(得分:2)
您可以使用caretPosition找到光标位置。请尝试以下代码。
[DllImport("user32.dll", EntryPoint = "GetGUIThreadInfo")]
public static extern bool GetGUIThreadInfo(uint tId, out GUITHREADINFO threadInfo);
[StructLayout(LayoutKind.Sequential)] // Required by user32.dll
public struct RECT
{
public uint Left;
public uint Top;
public uint Right;
public uint Bottom;
};
[StructLayout(LayoutKind.Sequential)] // Required by user32.dll
public struct GUITHREADINFO
{
public uint cbSize;
public uint flags;
public IntPtr hwndActive;
public IntPtr hwndFocus;
public IntPtr hwndCapture;
public IntPtr hwndMenuOwner;
public IntPtr hwndMoveSize;
public IntPtr hwndCaret;
public RECT rcCaret;
};
private System.Windows.Point EvaluateCaretPosition()
{
caretPosition = new Point();
try
{
// Fetch GUITHREADINFO
GetCaretPosition();
caretPosition.X = (int)guiInfo.rcCaret.Left; //+ 25;
caretPosition.Y = (int)guiInfo.rcCaret.Bottom; //+ 25;
WinApiDelegate.ClientToScreen(guiInfo.hwndCaret, ref caretPosition);
}
catch (Exception Ex)
{
GenerateConsolidatedErrorLog(Ex);
}
return new System.Windows.Point(caretPosition.X, caretPosition.Y);
}
public void GetCaretPosition()
{
try
{
guiInfo = new WinApiDelegate.GUITHREADINFO();
guiInfo.cbSize = (uint)Marshal.SizeOf(guiInfo);
// Get GuiThreadInfo into guiInfo
WinApiDelegate.GetGUIThreadInfo(0, out guiInfo);
}
catch (Exception Ex)
{
GenerateConsolidatedErrorLog(Ex);
}
}