好不容易有个周末,想联机打一把魔兽。可QQ对战平台上我想进去的几个房间都是人满为患,没办法,只好写个工具挤房间了。
原理很简单,就是调用keybd_event和mouse_event来不停的发鼠标点击(房间登录)和回车消息(登录失败确认)。代码如下:
class QQGameLoger
{
void TryLogIn()
{
ClickKey(Keys.Enter);
ClickLeftMouse();
}
bool enabled = false;
public bool Enabled
{
get
{
return enabled;
}
set
{
if (value)
Start();
else
Stop();
}
}
public void Start()
{
if (enabled)
return;
enabled = true;
System.Threading.ThreadPool.QueueUserWorkItem(x =>
{
try
{
while (true)
{
if (!Enabled)
break;
System.Threading.Thread.Sleep(200);
TryLogIn();
}
}
catch (Exception)
{
enabled = false;
}
});
}
public void Stop()
{
enabled = false;
}
void ClickKey(Keys key)
{
const int ExtendKey = 0x1;
const int KeyUp = 0x2;
keybd_event(key, 0x45, ExtendKey, 0);
keybd_event(key, 0x45, ExtendKey | KeyUp, 0);
}
[DllImport("user32.dll")]
static extern void keybd_event(Keys key, byte bScan, uint dwFlags,
uint dwExtraInfo);
[DllImport("user32.dll")]
static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData,
int dwExtraInfo);
[Flags]
public enum MouseEventFlags
{
LEFTDOWN = 0x00000002,
LEFTUP = 0x00000004,
MIDDLEDOWN = 0x00000020,
MIDDLEUP = 0x00000040,
MOVE = 0x00000001,
ABSOLUTE = 0x00008000,
RIGHTDOWN = 0x00000008,
RIGHTUP = 0x00000010
}
void ClickLeftMouse()
{
mouse_event((uint)MouseEventFlags.LEFTDOWN, 0, 0, 0, 0);
mouse_event((uint)MouseEventFlags.LEFTUP, 0, 0, 0, 0);
}
}
整个代码用.net实现,虽然调用api不如c++来得直接,但是要节省不少设计和调试时间。整个工具从设计到调试完成也没花多少时间,大部分时间花在查询和实验api的用法上了。
使用这段代码也很简单,只要把鼠标放在想登陆的房间上,注册个全局快捷键来调用start和stop即可。这个功能也集成在我以前写的魔兽鼠标限定的小工具上了。