GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 22-Feb-2006, 12:04
Levia Levia is offline
Junior Member
 
Join Date: Jan 2006
Posts: 65
Levia is on a distinguished road

Keyboard hook weird problems.


Im creating a hook to catch the text from users input when pressed F8, and it gets sent to a mirc channel window's edit box as soon as you press F7.But there are two weird problems

First one is that it doesnt work on background.F8 works on background, but the code in the hook doesnt work at background..Whats wrong?

Second, when I press F8 then type something then press F7, everything goes fine, but when I want to do it another time, without restarting, I get this error message sound as soon as I press F7, but nothing happens.I checked, and it did write the file, also checked if it executed the send messages, and it did.Whats wrong?

Pasting the whole code here.Including headers.
/\DLL
-=============DLLMAIN.CPP
CPP / C++ / C Code:
#include <windows.h> 
#include <fstream>
#include "dll.h"	
using namespace std;

ofstream KeyboardInput;	
HHOOK hHook;
HINSTANCE ghDLLInst=0;


BOOL WINAPI DllMain(HANDLE hModule, DWORD dwFunction, LPVOID lpNot)
{ 
    ghDLLInst=(HINSTANCE)hModule;
    return TRUE; 
} 

LRESULT CALLBACK KeyboardHook(int nCode, WPARAM wParam, LPARAM lParam) 
{
	KeyboardInput.open("text.txt", ofstream::app);
	if ((lParam < 1) && (nCode >= 0))	
	{
		if(wParam == VK_CONTROL || wParam == VK_ESCAPE)
		{
			return 0;
		}
		else
		{
			BYTE KeyboardState[256];
			GetKeyboardState(KeyboardState);
			WORD CharValue;
		
			if(ToAscii(wParam,0,KeyboardState,&CharValue,0) > 0)
			{
				KeyboardInput << (char)CharValue;
				KeyboardInput.close();
				return 1;
			}
		}
	}  
	KeyboardInput.close();
    return (int)CallNextHookEx(hHook, nCode, wParam, lParam); 
} 

__declspec(dllexport)int InstallHook(BOOL bCode)
{ 
    if(bCode) 
    { 
        hHook=(HHOOK)SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardHook,
                        ghDLLInst, GetCurrentThreadId());
        if(!hHook) {
            return 0;    
        } else {
            return 1;
        }
    } 
    else 
    { 
        return UnhookWindowsHookEx(hHook);
    } 
} 



-===============DLL.H
CPP / C++ / C Code:
#ifndef dll_H
#define dll_H

__declspec(dllexport)int InstallHook(BOOL bCode);		// __declspec(dllexport) means that this function must be exported to a dll

#endif


/\Program
-================MAIN.CPP
CPP / C++ / C Code:
#include <string>
#include <iostream>
#include <fstream>
#include <windows.h>
#include "mainh.h"


using namespace std;

HINSTANCE hThisInstance;
HWND hwnd;
ifstream fin;
ofstream ofin;

int SendMessage(void);

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT paintStruct;
    HDC hDC;
    char text1[ ] = "Program will activate when F8 is pressed.";
    switch (message)
    {

        case WM_CREATE:
            if (RegisterHotKey(hwnd, VK_F8, 0, VK_F8) == 0) {
                int err = GetLastError();
                MessageBox(hwnd, "Failed", "Error", MB_OK);
                ofin.open("error.txt");
                ofin << err;
                ofin.close();
            }
            if (RegisterHotKey(hwnd, VK_F7, 0, VK_F7) == 0) {
                int err = GetLastError();
                MessageBox(hwnd, "Failed", "Error", MB_OK);
                ofin.open("error.txt");
                ofin << err;
                ofin.close();
            }
            CreateWindowEx(0,                                      //more or 'extended' styles
                       TEXT("BUTTON"),                         //'class' of control to create
                       TEXT("Main"),                      //the control caption
                       WS_CHILD|WS_VISIBLE|BS_GROUPBOX,        //control style: how it looks
                       2,                                    //control position: left
                       0,                                      //control position: top
                       290,                                    //control width
                       50,                                     //control height
                       hwnd,                                   //parent window handle
                       NULL,                                   //control's ID
                       hThisInstance,                                //application instance
                       NULL
            );
            break;
        case WM_COMMAND:           
            break;
        case WM_HOTKEY:
            if (wParam == VK_F8) {
                ofin.open("text.txt");
                if (ofin.is_open()) {
                    ofin << "";
                    ofin.close();
                }
                InstallHook(TRUE);
            }
            if (wParam == VK_F7) {
                if (SendMessage() != 1) {
                    MessageBox(hwnd, "Failed to send", "Error", MB_OK);
                    int err = GetLastError();
                    ofin.open("Error.log");
                    ofin << err;
                    ofin.close();
                }
                InstallHook(FALSE);
            }
            break;
        case WM_DESTROY:
            UnregisterHotKey(hwnd, VK_F8);
            UnregisterHotKey(hwnd, VK_F7);

            InstallHook(FALSE);
            PostQuitMessage (0);
            break;
        case WM_CLOSE:
            break;
        case WM_PAINT:  
			hDC = BeginPaint(hwnd,&paintStruct);
            SetBkMode(hDC, TRANSPARENT);
			SetTextColor(hDC, COLORREF(0x00000000));
            TextOut(hDC,6,15,text1,sizeof(text1)-1);
			EndPaint(hwnd, &paintStruct);
			return 0;
			break;

        default:
            break;
    }
    return DefWindowProc(hwnd,message,wParam,lParam);
}


char szClassName[ ] = "MMChat";

int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nFunsterStil)

{             
    MSG messages;            
    WNDCLASSEX wincl;        

    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      
    wincl.style = CS_DBLCLKS;                 
    wincl.cbSize = sizeof (WNDCLASSEX);

    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 
    wincl.cbClsExtra = 0;                      
    wincl.cbWndExtra = 0;                      
    wincl.hbrBackground = HBRUSH(COLOR_3DFACE + 1); 
    
    if (!RegisterClassEx (&wincl))
        return 0;

    hwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "MMChat",       /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           300,                 /* The programs width */
           85,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL
           );

    ShowWindow (hwnd, nFunsterStil);

    while (GetMessage (&messages, NULL, 0, 0))
    {

        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}

/* Functions */
int SendMessage (void) {
    string line;        
    fin.open("text.txt");
    if (fin.is_open()) {
        getline (fin,line);
    }
    HWND mainHandle = FindWindow("mIRC", NULL);
    HWND serverHandle = FindWindowEx(mainHandle, NULL, "MDIClient", NULL);
    HWND chanHandle = FindWindowEx(serverHandle, NULL, "mIRC_Channel" ,NULL);
    HWND editHandle = FindWindowEx(chanHandle, NULL, "Edit", NULL);
    if (serverHandle == 0) {
        MessageBox(hwnd, "Unable to retrieve handle of MDIClient", "Error", MB_OK);
        return 0;
    } else {
        if (chanHandle == 0) {
            MessageBox(hwnd, "Unable to retrieve handle of mIRC_Channel", "Error", MB_OK);
            return 0;
        } else {
            if (editHandle == 0) {
                MessageBox(hwnd, "Unable to retrieve handle of Editbox", "Error", MB_OK);
                return 0;
            } else {
                SendMessage(editHandle, WM_SETTEXT, 0, (LPARAM)line.c_str());
                SendMessage(editHandle, WM_IME_KEYDOWN, VK_RETURN, 0);
                return 1;
            }
        }
        if (fin.is_open()) {
            fin.close();
        }
    }
    return 0;
}



-===============mainh.h
CPP / C++ / C Code:
#ifndef MAINH_H
#define MAINH_H

// InstallHook needs to be imported from a dll.
__declspec(dllimport) int InstallHook(BOOL bCode);

#endif



Sorry that I pasted this much code, but I feel like it can be in either the DLL or the program.
  #2  
Old 23-Feb-2006, 20:57
TurboPT's Avatar
TurboPT TurboPT is offline
Regular Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 995
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Keyboard hook weird problems.


Not sure about all the 'hooking', but could GetAsyncKeyState() possibly work for you? I'll have to post more later, for I can't get into specifics right now.
  #3  
Old 25-Feb-2006, 12:53
Levia Levia is offline
Junior Member
 
Join Date: Jan 2006
Posts: 65
Levia is on a distinguished road

Re: Keyboard hook weird problems.


GetAsyncKeyState is only for 1 key, not for the all of them at the same time??
  #4  
Old 25-Feb-2006, 19:17
TurboPT's Avatar
TurboPT TurboPT is offline
Regular Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 995
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Keyboard hook weird problems.


I guess I may not be sure about what you are trying to accomplish, but I assumed you were looking for only the F7 & F8 keys?

I was thinking something along these lines:
CPP / C++ / C Code:
      
      if (GetAsyncKeyState(VK_F7) < 0)
      {
           // handle the F7 key press.
      }
      else if (GetAsyncKeyState(VK_F8) < 0)
      {
          // handle the F8 key press.
      }
  #5  
Old 26-Feb-2006, 00:31
Levia Levia is offline
Junior Member
 
Join Date: Jan 2006
Posts: 65
Levia is on a distinguished road

Re: Keyboard hook weird problems.


No not really.The F8 and F7 keys work fine, but its about the 'normal' keys like 'a' and so on, I need to track those.Thats done in the DLL with GetKeyboardState() which copies all button values to a variable.THAT one doesnt work on background.
  #6  
Old 27-Feb-2006, 15:40
ubergeek ubergeek is offline
Regular Member
 
Join Date: Jan 2005
Posts: 775
ubergeek is a jewel in the roughubergeek is a jewel in the roughubergeek is a jewel in the rough

Re: Keyboard hook weird problems.


I think you're trying to capture the string the user types after F7 and before F8, right? Not just one character? If I'm right, GetKeyboardState() is not what you want. That just takes a "snapshot" of the keyboard. You probably need to create a window with a text box to capture the input.

By the way, defining a function SendMessage(), which is the same name as the very common Win32 function, is probably a bad idea (while C++ overloading will sort it out, the same name in your code will get confusing)
  #7  
Old 28-Feb-2006, 04:24
Levia Levia is offline
Junior Member
 
Join Date: Jan 2006
Posts: 65
Levia is on a distinguished road

Re: Keyboard hook weird problems.


ubergeek: ..It is the other way aroundBut that doesnt matter.F8 -> "Type something you like" -> F7
But yes, I wanna the capture the string after F8 and before F7.And I want it to work on background That is the whole problem.The F8 and F7 do work on background, only the capturing dont.

I dont think the textbox will catch the keys on background?
But using such a textbox would be more efficient, as i dont have to use the file writing anylonger, but it must work on background.
  #8  
Old 28-Feb-2006, 15:08
ubergeek ubergeek is offline
Regular Member
 
Join Date: Jan 2005
Posts: 775
ubergeek is a jewel in the roughubergeek is a jewel in the roughubergeek is a jewel in the rough

Re: Keyboard hook weird problems.


why not do this (pseudocode):
Code:
OnPressF8 SetFlag(already pressed F8) CreateWindow(small, middle of screen) CreateEditBox(in above window) End_OnPressF8 OnPressF7 IfNot (already pressed F8) Break GetText(from edit box) SetText(gotten in above statement, to mirc window) DestroyWindow(the one created in OnPressF8) ClearFlag(already pressed F8) End_OnPressF7
I hope my psuedocode is comprehensible. By the way, you could eliminate the flag by simply checking whether your window exists.

My way, the program site in the background listening for F8, and then it comes to the foreground to capture text (this way the user can see what they are typing, as well) and then goes away again when F7 is pressed
  #9  
Old 01-Mar-2006, 03:28
Levia Levia is offline
Junior Member
 
Join Date: Jan 2006
Posts: 65
Levia is on a distinguished road

Re: Keyboard hook weird problems.


Its a very good idea.I perfectly understand what you are trying to do, which is very smart.Ill try it today, and paste the code asap, so you can see what happened to it.

Ill try it, but im not sure whether the game will alt-tab after showing the window.
  #10  
Old 01-Mar-2006, 06:56
Levia Levia is offline
Junior Member
 
Join Date: Jan 2006
Posts: 65
Levia is on a distinguished road

Re: Keyboard hook weird problems.


Made the program, but as I already thought, showing it in the game is a problem

CPP / C++ / C Code:
#include <string>
#include <iostream>
#include <fstream>
#include <windows.h>


using namespace std;

HINSTANCE hThisInstance;
HWND hwnd;
HWND CWindow;
HWND EBox;
ifstream fin;
ofstream ofin;

int SendMessage(void);
int CreateWnd(void);

LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT paintStruct;
    HDC hDC;
    int pressed = 0;
    char text1[ ] = "Program will activate when F8 is pressed.";
    switch (message)
    {

        case WM_CREATE:
            if (RegisterHotKey(hwnd, VK_F8, 0, VK_F8) == 0) {
                int err = GetLastError();
                MessageBox(hwnd, "Failed", "Error", MB_OK);
                ofin.open("error.txt");
                ofin << err;
                ofin.close();
            }
            if (RegisterHotKey(hwnd, VK_F7, 0, VK_F7) == 0) {
                int err = GetLastError();
                MessageBox(hwnd, "Failed", "Error", MB_OK);
                ofin.open("error.txt");
                ofin << err;
                ofin.close();
            }
            CreateWindowEx(0,                                      //more or 'extended' styles
                       TEXT("BUTTON"),                         //'class' of control to create
                       TEXT("Main"),                      //the control caption
                       WS_CHILD|WS_VISIBLE|BS_GROUPBOX,        //control style: how it looks
                       2,                                    //control position: left
                       0,                                      //control position: top
                       290,                                    //control width
                       50,                                     //control height
                       hwnd,                                   //parent window handle
                       NULL,                                   //control's ID
                       hThisInstance,                                //application instance
                       NULL
            );
            break;
        case WM_COMMAND:           
            break;
        case WM_HOTKEY:
            if (wParam == VK_F8) {
                pressed = 1;
                CreateWnd();
            }
            if ((wParam == VK_F7) && (pressed == 1)) {
                
            }
            break;
        case WM_DESTROY:
            UnregisterHotKey(hwnd, VK_F8);
            UnregisterHotKey(hwnd, VK_F7);

            PostQuitMessage (0);
            break;
        case WM_CLOSE:
            break;
        case WM_PAINT:  
			hDC = BeginPaint(hwnd,&paintStruct);
            SetBkMode(hDC, TRANSPARENT);
			SetTextColor(hDC, COLORREF(0x00000000));
            TextOut(hDC,6,15,text1,sizeof(text1)-1);
			EndPaint(hwnd, &paintStruct);
			return 0;
			break;

        default:
            break;
    }
    return DefWindowProc(hwnd,message,wParam,lParam);
}


char szClassName[ ] = "MMChat";

int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nFunsterStil)

{             
    MSG messages;            
    WNDCLASSEX wincl;        

    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = szClassName;
    wincl.lpfnWndProc = WindowProcedure;      
    wincl.style = CS_DBLCLKS;                 
    wincl.cbSize = sizeof (WNDCLASSEX);

    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 
    wincl.cbClsExtra = 0;                      
    wincl.cbWndExtra = 0;                      
    wincl.hbrBackground = HBRUSH(COLOR_3DFACE + 1); 
    
    if (!RegisterClassEx (&wincl))
        return 0;

    hwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "MMChat",       /* Title Text */
           WS_OVERLAPPEDWINDOW, /* default window */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           300,                 /* The programs width */
           85,                 /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           NULL,                /* No menu */
           hThisInstance,       /* Program Instance handler */
           NULL
           );

    ShowWindow (hwnd, nFunsterStil);

    while (GetMessage (&messages, NULL, 0, 0))
    {

        TranslateMessage(&messages);
        /* Send message to WindowProcedure */
        DispatchMessage(&messages);
    }

    /* The program return-value is 0 - The value that PostQuitMessage() gave */
    return messages.wParam;
}

/* Functions */
int SendMessage (void) {
    string line;        
    fin.open("text.txt");
    if (fin.is_open()) {
        getline (fin,line);
    }
    HWND mainHandle = FindWindow("mIRC", NULL);
    HWND serverHandle = FindWindowEx(mainHandle, NULL, "MDIClient", NULL);
    HWND chanHandle = FindWindowEx(serverHandle, NULL, "mIRC_Channel" ,NULL);
    HWND editHandle = FindWindowEx(chanHandle, NULL, "Edit", NULL);
    if (serverHandle == 0) {
        MessageBox(hwnd, "Unable to retrieve handle of MDIClient", "Error", MB_OK);
        return 0;
    } else {
        if (chanHandle == 0) {
            MessageBox(hwnd, "Unable to retrieve handle of mIRC_Channel", "Error", MB_OK);
            return 0;
        } else {
            if (editHandle == 0) {
                MessageBox(hwnd, "Unable to retrieve handle of Editbox", "Error", MB_OK);
                return 0;
            } else {
                SendMessage(editHandle, WM_SETTEXT, 0, (LPARAM)line.c_str());
                //SendMessage(editHandle, WM_IME_KEYDOWN, VK_RETURN, 0);
                return 1;
            }
        }
        if (fin.is_open()) {
            fin.close();
        }
    }
    return 0;
}

LRESULT CALLBACK ChatWindowProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT paintStruct;
    HDC hDC;
    switch (message)
    {
        case WM_CREATE:
            EBox = CreateWindowEx(
                       WS_EX_CLIENTEDGE,                      //more or 'extended' styles
                       TEXT("EDIT"),                          //'class' of control to create
                       0,    //the control caption
                       WS_CHILD|WS_VISIBLE|WS_BORDER|         //control style: how it looks
                       ES_MULTILINE,
                       0,                                    //control position: left
                       0,                                    //control position: top
                       240,                                   //control width
                       85,                                    //control height
                       hwnd,                                  //parent window handle
                       NULL,                                  //control's ID
                       hThisInstance,                               //application instance
                       NULL
            );
            if (!EBox) {
                int err = GetLastError();
                MessageBox(hwnd, "Failed", "Failed", MB_OK);
                ofin.open("errors.log");
                ofin << err;
                ofin.close();
            }
            SetWindowPos(EBox, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOMOVE);
            SetFocus(EBox);
            break;
        default:
            break;
    }
    return DefWindowProc(hwnd,message,wParam,lParam);
}






int CreateWnd(void) {
    char WindowClassname[ ] = "Type";
    WNDCLASSEX wincl;        

    wincl.hInstance = hThisInstance;
    wincl.lpszClassName = WindowClassname;
    wincl.lpfnWndProc = ChatWindowProc;      
    wincl.style = CS_DBLCLKS;                 
    wincl.cbSize = sizeof (WNDCLASSEX);

    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
    wincl.lpszMenuName = NULL;                 
    wincl.cbClsExtra = 0;                      
    wincl.cbWndExtra = 0;                      
    wincl.hbrBackground = HBRUSH(COLOR_3DFACE + 1); 
    
    if (!RegisterClassEx (&wincl)) {
        return 0;
    }

    CWindow = CreateWindowEx(
        0,
        WindowClassname,
        "Type",
        WS_OVERLAPPEDWINDOW | WS_EX_TOPMOST,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        250,
        120,
        hwnd,
        NULL,
        hThisInstance,
        NULL
    );
    ShowWindow(CWindow,1);
    //SetForegroundWindow(CWindow);
    //BringWindowToTop(CWindow);
    if (!CWindow) {
        int err = GetLastError();
        MessageBox(hwnd, "Failed", "Failed", MB_OK);
        ofin.open("errors.log");
        ofin << err;
        ofin.close();
    }
}

Dont pay any attention to those file write stuff, there just to test, ill remove em later.
 
 

Recent GIDBlogToyota - 2008 November Promotion by Nihal

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Problems while burning CD's netnut Computer Software Forum - Windows 16 18-Jan-2008 00:45
Problems with my first pc build davro Computer Hardware Forum 5 29-Jul-2006 15:11
Weird Toolbar and Statusbar autosizing Problems Szabadember C++ Forum 1 26-Jul-2005 15:56
Chaintech Geforce 5600 FX problems bartster74 Computer Hardware Forum 8 04-May-2004 14:16
list of the most common keyboard and mouse shortcuts for IE, Opera and Firebird jrobbio Computer Software Forum - Windows 2 04-Sep-2003 10:10

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 10:06.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.