VC++模拟键盘消息

VC++中使用INPUT 结构体可以模拟鼠标和键盘消息,INPUT结构体结构如下:
typedef struct tagINPUT {
  DWORD   type;
  union {
      MOUSEINPUT      mi;
      KEYBDINPUT      ki;
      HARDWAREINPUT   hi;
  };
} INPUT, *PINPUT;
虽然INPUT结构体可以模拟每一个我们可以输入的消息,但一个结构体变量只能表示一个消息,而且实现起来比较麻烦,所以对他进行了简单的封装,写了一个简单的类,用于简化实现模拟消息的操作:
class InputManager  
{
public:
	InputManager();
	InputManager(int,int);
	virtual ~InputManager();
private:
	INPUT m_Input;
public:
	void SendDown();
	void SendUp();
	void SetValue(int type,int VK_);
	int GetwVk();
	void SetvVk(int a);
};
InputManager::InputManager()
{
}

InputManager::InputManager(int type,int VK_)
{
	m_Input.type = type ;
	m_Input.ki.wVk=VK_;
	m_Input.ki.dwFlags=0 ;
	m_Input.ki.time =::GetTickCount();
	m_Input.ki.dwExtraInfo = 0 ;
}
InputManager::~InputManager()
{
}
void InputManager::SendDown()
{
	m_Input.ki.dwFlags=0;
	::SendInput(1,&m_Input,sizeof(INPUT));		
}
void InputManager::SendUp()
{
	m_Input.ki.dwFlags=KEYEVENTF_KEYUP;
	::SendInput(1,&m_Input,sizeof(INPUT));		
}
void InputManager::SetValue(int type,int VK_)
{
	m_Input.type = type ;
	m_Input.ki.wVk=VK_;
	m_Input.ki.dwFlags=0 ;
	m_Input.ki.time =::GetTickCount();
	m_Input.ki.dwExtraInfo = 0 ;
}
int InputManager::GetwVk()
{
	return m_Input.ki.wVk;
}
void InputManager::SetvVk(int a)
{
	m_Input.ki.wVk=a;
}
在模拟一个字符(A)消息时,就可以直接这样处理:
InputManager i(INPUT_KEYBOARD,VK_A);
i.SendDown();//A按下
i.SendUp();A松开
 
  
在此基础上,在对InputManager进一步封装,就可以实现一次模拟输入字符串的消息了。
class StringInput  
{
public:
	StringInput(CString str,int length);
	virtual ~StringInput();
private:
	InputManager *m_pInputManager;
	int InputNumber;
public:
	void Send();
	//void SendUp();
};
StringInput::StringInput(CString str,int length)
{
	this->m_pInputManager=new InputManager[length];
	InputNumber=length;
	for(int i=0;i<InputNumber;i++)
	{
		int a=(int)str.GetAt(i);
		this->m_pInputManager[i].SetValue(INPUT_KEYBOARD,a);
	}
}

StringInput::~StringInput()
{
	//delete m_pInputManager;
}

void StringInput::Send()
{
	for(int i=0;i<InputNumber;i++)
	{
		int VKValue=m_pInputManager[i].GetwVk();
		if(VKValue>=65 && VKValue<=90)
		{
			InputManager im_shift(INPUT_KEYBOARD,VK_SHIFT);
			im_shift.SendDown();
			this->m_pInputManager[i].SendDown();
			this->m_pInputManager[i].SendUp();
			im_shift.SendUp();
		}
		else
		{
			if(VKValue<=122 && VKValue>=97)
			{
				this->m_pInputManager[i].SetvVk(VKValue-32);
			}
			if(VKValue==46)
			{
				this->m_pInputManager[i].SetvVk(110);
			}
			this->m_pInputManager[i].SendDown();
			this->m_pInputManager[i].SendUp();
		}
		Sleep(100);
	}
}
比如,如果想实现自动输入一个“Microsoft”字符串,可以这样实现:
CString str("Microsoft")
StringInput si(str,str.GetLength());
si.Send();//相当于用键盘输入“Microsoft”。

猜你喜欢

转载自blog.csdn.net/u010757019/article/details/52398117
今日推荐