the situation is that,when I operate a mouse hook,I find that there are two types of current thread id ,codes below:
Thread.CurrentThread.ManagedThreadId
AppDomain.GetCurrentThreadId()
the ids are defferent with each other,why?
Entering the mouse hook procedure two times,codes below:
public partial class Form1 : Form
{
MOUSEHOOK mouseHook = new MOUSEHOOK();
MOUSEHOOK.HookHandle hookhandle = null;
MOUSEHOOK.MouseHookStruct mhs = new MOUSEHOOK.MouseHookStruct();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
hookhandle = new MOUSEHOOK.HookHandle(HookProc);
if (true == mouseHook.InstallHook(hookhandle))
{
Console.WriteLine("successed");
}
Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
Console.WriteLine(AppDomain.GetCurrentThreadId().ToString());
}
int HookProc(int nCode, int wParam, IntPtr lParam)
{
Marshal.PtrToStructure(lParam, mhs);
switch (wParam)
{
case MOUSEHOOK.WM_LBUTTONUP:
Console.WriteLine("how many times to enter?");
break;
default :
break;
}
return MOUSEHOOK.CallNextHookEx(0, nCode, wParam, lParam);
}
}
public class MOUSEHOOK
{
[DllImport("user32.dll")]
private static extern int SetWindowsHookEx(int idHook, HookHandle HookProc, IntPtr hMod, int dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll")]
public static extern int CallNextHookEx(int idHook, int nCode, int wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
public static extern int GetCurrentThreadId();
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
public POINT pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
public const int WH_MOUSE = 7;
public const int WM_MOUSEMOVE = 0x200;
public const int WM_LBUTTONDOWN = 0x201;
public const int WM_LBUTTONUP = 0x202;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int WM_NCLBUTTONUP = 0xA2;
public const int WM_NCMOUSEMOVE = 0xA0;
public MouseHookStruct mhs = new MouseHookStruct();
public int hhook;
public delegate int HookHandle(int nCode, int wParam, IntPtr lParam);
public bool InstallHook(HookHandle MouseProc)
{
hhook = SetWindowsHookEx(WH_MOUSE, MouseProc, IntPtr.Zero, GetCurrentThreadId());
if (hhook != 0)
return true;
return false;
}
public void UnInstallHook()
{
bool ret = false;
if (hhook != 0)
ret = UnhookWindowsHookEx(hhook);
if (ret)
hhook = 0;
}
}