一个控制台下接受消息的问题。。。我想试试用控制台接收windows发来的消息。。。我用windows程序设计那本书上的h
一个控制台下接受消息的问题。。。
我想试试用控制台接收windows发来的消息。。。
我用windows程序设计那本书上的hook例子,也就是键盘钩子,每次收到消息后发送到主程序那里。。。不过在console下却没有任何作用。。。为啥:》??
hook的回调函数:
C/C++ codeLRESULT CALLBACK KeyHookProc(int nCode, WPARAM wParam, LPARAM lParam){ if(nCode<0 || nCode == HC_NOREMOVE) return ::CallNextHookEx(g_hHook, nCode, wParam, lParam); if(lParam & 0x40000000)//消息重复的情况下,交给下个hook return ::CallNextHookEx(g_hHook, nCode, wParam, lParam); //通知主窗口,wParam参数为虚拟键码,lParam参数包含了它的信息 ::PostMessage(g_hWndCaller, HM_KEY, wParam, lParam); return ::CallNextHookEx(g_hHook, nCode, wParam, lParam);}
主程序的代码:
C/C++ code#include "hook.h"#include <iostream>using namespace std;HWND g_hwnd;int main(){ g_hwnd = GetConsoleHwnd();//这个函数也是dll里的,得到控制台的句柄 char buf[MAX_PATH]; GetWindowText(g_hwnd, buf,sizeof(buf)); cout<<(char*)buf<<endl; if(SetKeyHook(true, 0, g_hwnd)) { MSG msg; while(GetMessage(&msg,NULL,0,0)) { switch(msg.message) { //无效 case HM_KEY: GetKeyNameText(msg.lParam,buf,sizeof(buf)); cout<<buf<<endl; } } } else cout<<"Faild";}
[解决办法]控制台没有消息循环,你在程序的开头先调用一下MessageBox函数,好像这样就有消息循环了,你试试
[解决办法]控制台可以接受消息,只不过自己接受处理消息
#include <windows.h>
#include <stdio.h>
#include <conio.h>
unsigned long WINAPI Thread(PVOID pvoid);
void main()
{
DWORD dwThreadId;
printf("use timer in workthread of console application<masterz>\n");
HANDLE hThread = CreateThread(
NULL, // no security attributes
0, // use default stack size
Thread, // thread function
0, // argument to thread function
0, // use default creation flags
&dwThreadId);
DWORD dwwait=WaitForSingleObject(hThread,1000*30);
switch(dwwait)
{
case WAIT_ABANDONED:
printf("main thread WaitForSingleObject return WAIT_ABANDONED\n");
break;
case WAIT_OBJECT_0:
printf("main thread WaitForSingleObject return WAIT_OBJECT_0\n");
break;
case WAIT_TIMEOUT:
printf("main thread WaitForSingleObject return WAIT_TIMEOUT\n");
break;
}
CloseHandle(hThread);
_getch();
}
unsigned long WINAPI Thread(PVOID pvoid)
{
MSG msg;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
UINT timerid=SetTimer(NULL,111,3000,NULL);
BOOL bRet;
int count =0;
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
if(msg.message==WM_TIMER)
{
count++;
printf("WM_TIMER in work thread count=%d\n",count);
if(count>4)
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
KillTimer(NULL,timerid);
printf("thread end here\n");
return 0;
}
[解决办法]
控制台哪有句柄啊 又没有window 怎么会有windowhandle
[解决办法]
好冲的人啊 够霸气~
createwindow啊~~ 我是菜鸟 所以对我而言难用 尤其是那一坨一坨的参数 ~~~
我是在说控制台没句柄 你怎么就扯到了createwindow呢?
控制台都是csr那边的东西啊~~~ 麻烦你先研究清楚好吧 第一次听说有人用createwindow创建控制台的……
[解决办法]