C# 当代码放置在外部dll中时SetWindowsHookEx不工作
在表单应用程序中,当代码放置在该项目中时,这似乎可以很好地工作。但是,当代码放在控制台库中并添加引用时,它就不起作用了。。 我尝试将DLL添加到windows窗体等中,并使用静态等,但当其C# 当代码放置在外部dll中时SetWindowsHookEx不工作,c#,.net,winforms,C#,.net,Winforms,在表单应用程序中,当代码放置在该项目中时,这似乎可以很好地工作。但是,当代码放在控制台库中并添加引用时,它就不起作用了。。 我尝试将DLL添加到windows窗体等中,并使用静态等,但当其 放置在dll中的控制台应用程序实际上不是为鼠标输入而设计的。我认为@Frank Krueger的评论值得考虑。他的评论是针对某个问题的……你可能会发现这很有帮助。。阅读与hMod和dwThreadId相关的说明。这些因素共同作用。另请参见:和(与WH\u MOUSE\u LL相同)。您似乎还缺少该代码中的许多
放置在dll中的控制台应用程序实际上不是为鼠标输入而设计的。我认为@Frank Krueger的评论值得考虑。他的评论是针对某个问题的……你可能会发现这很有帮助。。阅读与
hMod
和dwThreadId
相关的说明。这些因素共同作用。另请参见:和(与WH\u MOUSE\u LL
相同)。您似乎还缺少该代码中的许多片段。这个应用程序有什么用?也许你想要一个build a.dll
来代替它?从这里开始声明:@Frank Krueger我创建了一个C#library并将此代码移到了那里,并在WINDOWS窗体应用程序中添加了它的引用build adll
,而不是控制台应用程序。仔细阅读有关这两个参数(hMod
和dwThreadId
)的文档。在库中使用时,它们的工作方式有所不同(如文档中明确描述的)。注意,文档说明调用CallNextHookEx()
是可选的。实际上不是。请参阅我之前链接的实现以及这一个:(关于释放分配的资源/处理程序)。
HI i have a following code that reads mouse event
using System;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
public enum MouseKeyType
{
MouseMoveOnly=512,
MouseLeftKeyDown=513,
MouseLeftKeyup=514,
MouseRightKeyDown = 516,
MouseRightKeyup = 517,
MouseMiddleKeyDown = 519,
MouseMiddleKeyup = 520,
MouseScroll=522
}
[StructLayout(LayoutKind.Sequential)]
public class MouseEventData
{
public Point point;
private int mouseData;
private int flags;
public int time;
//public int dwExtraInfo;
public bool IsScrollUp
{
get
{
return mouseData > -1;
}
}
public MouseKeyType mouseKeyType;
}
public class gc
{
// Event
public delegate void gcMouseEvents(object source, MouseEventData e);
public event gcMouseEvents gcevent;
// WIN32 hook
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int SetWindowsHookEx( int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);
//just a delegate to simplify the type of
private delegate int HookProc(int nCode,int wParam, IntPtr lParam);
private HookProc _hookCallback;
public gc()
{
_hookCallback = new HookProc((x,y,z)=>
{
//string output = JsonConvert.SerializeObject(ptr);
//Console.WriteLine(output);
if (gcevent!=null)
{
MouseEventData ptr = (MouseEventData)Marshal.PtrToStructure(z, typeof(MouseEventData));
ptr.mouseKeyType = (MouseKeyType)y;
gcevent(this, ptr);
}
return 0;
});
SetWindowsHookEx(
14,
_hookCallback,
Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]),
0);
}
}