Dont know how to correctly edit this code - c

Well i am still slightly new in C.
Lets say i have this code:
source.c
#include "logger.c"
int main{
FILE *myfile1;
fileX = fopen("myfile.txt, a+);
SetHook(fileX);
}
and then i have very simple keylogger
logger.c
HHOOK _hook;
KBDLLHOOKSTRUCT kbdStruct;
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode >= 0)
{
if (wParam == WM_KEYDOWN)
{
// PRINT INTO THE FILE
kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
fprintf(fileX, "%c", kbdStruct.vkCode);
}
}
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
void SetHook(fileX)
{
_hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0)
}
Basically i want to have separated code like this.
But i think this is wrong i need to pass that "fileX" not to function setHOOK() but to that "LRESULT __stdcall..." and i dont know how to do that.
I will be thankfull for any help.

WH_KEYBOARD_LL is global hook you need place its hook procedure in a DLL separate from
the application installing the hook procedure. (For simple purpose you can put hook procedure in your application and it is also working. But this is not suggested way.)
(SetWindowsHookExA function Using Hooks)
This hook is called in the context of the thread that installed it.
The call is made by sending a message to the thread that installed the
hook. Therefore, the thread that installed the hook must have a
message loop. (In another word, the application need have a window so that it can keep pumping messages.)
(LowLevelKeyboardProc callback function)
For learning purpose of hook, my suggestion is getting started using Visual Studio Windows Desktop Application template (C++).
It is simple to register the keyboard hook and receive message in the hook.
And for writing to a file in the hook producer you can create a named file map so that you don't need to pass a file handle to the hook. You can open this file map using its name and write to the file using this file map. (Creating Named Shared Memory)
static HHOOK hhookKeyPress;
hhookKeyPress = SetWindowsHookEx(
WH_KEYBOARD_LL,
KeyboardHookCallback,
NULL,
0);
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
Sharing above information to help you get started and then you can find C programming way later. Hope it helps.

Related

Win32: Small Icon doesn't show

I'm learning Win32 programming
I used LoadImage(...) to set the small icon for the window but it doesn't seem to be working and I cannot pinpoint the problem
void AddIcons(HWND hw)
{
HICON hi = LoadImage(NULL, "ICON.bmp", IMAGE_BITMAP, 16, 16, LR_LOADFROMFILE);
printf("Icon initialized\n");
if(hi)
{
printf("%x\n", hi);
SendMessage(hw, WM_SETICON, ICON_SMALL, (LPARAM)hi);
}
}
And the windows procedure:
LRESULT CALLBACK WndProc(HWND handle, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_SETICON: printf("REQUEST RECEIVED\n");
}
.
. // AddIcons() is called here
. // DefWindowProc() handles the message at the end
}
I get all three print statements including REQUEST RECEIVED.
However, the icon is still the default. Where is the problem occuring?
I am aware that I can use keep a resource file and use LoadIcon(..) but I am more comfortable doing everything programatically. Which begs a second question:
Can everything that can be done using resource(.rc) files be done programmatically?
If so, is one method inherently better than the other?

How would I go about disabling the close button?

First of all, let me get my point for this:
This is an emergency alert system, it pulls from a website which we manipulate in the back office, the program can be minimized but cannot be closed (easily, at least none of the people that will use it will know how). As you can see, if the program was closed the Emergency Alerts wouldn't be seen/heard....that's an issue. I have to deploy this application on over 200 computers so I want it simple, I don't want to create a scheduled task, etc.. to keep it running. I simply want it to not be easy to close.
See my code, below:
/* example.c
This is a Win32 C application (ie, no MFC, WTL, nor even any C++ -- just plain C) that demonstrates
how to embed a browser "control" (actually, an OLE object) in your own window (in order to display a
web page, or an HTML file on disk). The bulk of the OLE/COM code is in DLL.c which creates a DLL that
we use in this simple app. Furthermore, we use LoadLibrary and GetProcAddress, so our DLL is not
actually loaded until/unless we need it.
NOTE: The DLL we create does not normally use UNICODE strings. If you compile this example as UNICODE,
then you should do the same with DLL.C.
*/
#include <windows.h>
#include "..\CWebPage.h" /* Declarations of the functions in DLL.c */
// A running count of how many windows we have open that contain a browser object
unsigned char WindowCount = 0;
// The class name of our Window to host the browser. It can be anything of your choosing.
static const TCHAR ClassName[] = "EAS";
// Where we store the pointers to CWebPage.dll's functions
EmbedBrowserObjectPtr *lpEmbedBrowserObject;
UnEmbedBrowserObjectPtr *lpUnEmbedBrowserObject;
DisplayHTMLPagePtr *lpDisplayHTMLPage;
DisplayHTMLStrPtr *lpDisplayHTMLStr;
/****************************** WindowProc() ***************************
* Our message handler for our window to host the browser.
*/
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_CREATE)
{
// Embed the browser object into our host window. We need do this only
// once. Note that the browser object will start calling some of our
// IOleInPlaceFrame and IOleClientSite functions as soon as we start
// calling browser object functions in EmbedBrowserObject().
if ((*lpEmbedBrowserObject)(hwnd)) return(-1);
// Another window created with an embedded browser object
++WindowCount;
// Success
return(0);
}
if (uMsg == WM_DESTROY)
{
// Detach the browser object from this window, and free resources.
(*lpUnEmbedBrowserObject)(hwnd);
// One less window
--WindowCount;
// If all the windows are now closed, quit this app
if (!WindowCount) PostQuitMessage(0);
return(TRUE);
}
// NOTE: If you want to resize the area that the browser object occupies when you
// resize the window, then handle WM_SIZE and use the IWebBrowser2's put_Width()
// and put_Height() to give it the new dimensions.
return(DefWindowProc(hwnd, uMsg, wParam, lParam));
}
/****************************** WinMain() ***************************
* C program entry point.
*
* This creates a window to host the web browser, and displays a web
* page.
*/
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hInstNULL, LPSTR lpszCmdLine, int nCmdShow)
{
HINSTANCE cwebdll;
MSG msg;
WNDCLASSEX wc;
// Load our DLL containing the OLE/COM code. We do this once-only. It's named "cwebpage.dll"
if ((cwebdll = LoadLibrary("cwebpage.dll")))
{
// Get pointers to the EmbedBrowserObject, DisplayHTMLPage, DisplayHTMLStr, and UnEmbedBrowserObject
// functions, and store them in some globals.
// Get the address of the EmbedBrowserObject() function. NOTE: Only Reginald has this one
lpEmbedBrowserObject = (EmbedBrowserObjectPtr *)GetProcAddress((HINSTANCE)cwebdll, "EmbedBrowserObject");
// Get the address of the UnEmbedBrowserObject() function. NOTE: Only Reginald has this one
lpUnEmbedBrowserObject = (UnEmbedBrowserObjectPtr *)GetProcAddress((HINSTANCE)cwebdll, "UnEmbedBrowserObject");
// Get the address of the DisplayHTMLPagePtr() function
lpDisplayHTMLPage = (DisplayHTMLPagePtr *)GetProcAddress((HINSTANCE)cwebdll, "DisplayHTMLPage");
// Get the address of the DisplayHTMLStr() function
lpDisplayHTMLStr = (DisplayHTMLStrPtr *)GetProcAddress((HINSTANCE)cwebdll, "DisplayHTMLStr");
// Register the class of our window to host the browser. 'WindowProc' is our message handler
// and 'ClassName' is the class name. You can choose any class name you want.
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.hInstance = hInstance;
wc.lpfnWndProc = WindowProc;
wc.lpszClassName = &ClassName[0];
RegisterClassEx(&wc);
// Create another window with another browser object embedded in it.
if ((msg.hwnd = CreateWindowEx(0, &ClassName[0], "Emergency Alert System", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
HWND_DESKTOP, NULL, hInstance, 0)))
{
// For this window, display a URL. This could also be a HTML file on disk such as "c:\\myfile.htm".
(*lpDisplayHTMLPage)(msg.hwnd, "http://www.google.com");
// Show the window.
ShowWindow(msg.hwnd, nCmdShow);
UpdateWindow(msg.hwnd);
}
// Do a message loop until WM_QUIT.
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Free the DLL.
FreeLibrary(cwebdll);
return(0);
}
MessageBox(0, "Can't open cwebpage.dll! You are not protected by Emergency Alerting System. Click OK to terminate this application. Contact the developer, Scott Plunkett.", "ERROR", MB_OK);
return(-1);
}
It took this from an example tutorial I found, I have never done any windows programming before so I had to figure out a quick solution.
I appreciate any and all help on this.
If you create a handler for the WM_SYSCOMMAND message and check for the SC_SYSCLOSE parameter, you can stop it from executing the default action of closing the window.
I noticed it's not an MFC application, so you have to call Win32 Library to enable the feature.
Try this out:http://www.davekb.com/browse_programming_tips:win32_disable_close_button:txt
---EDIT---
Sorry the code did not work out. I did not have resources to debug it.
To disable the X of the window, you can either set CS_NOCLOSE property of WNDCLASSEX:
wc.style = CS_NOCLOSE;//in your code
or rewrite the WM_CLOSE message handler function. Thanks.

How do I use SetWindowsHookEx to filter low-level key events?

I have this code which sets up a keyboard hook for low-level events, then displays a message box.
HHOOK keyboardHook = SetWindowsHookEx (WH_KEYBOARD_LL, HookKey, hInstance, 0);
MessageBox(NULL, L"Click to exit", L"hook test", NULL);
UnhookWindowsHookEx(keyboardHook);
How do I run the application's main loop without creating a foreground window, and how do I set hInstance to capture global events?
The answer is all contained on the MSDN docs page for SetWindowsHookEx. To experiment with a sample application, create a new solution, add two projects, a console app and a DLL. Each project just needs one file. The DLL will contain the hook, and the console app installs the hook.
The code for the hook must live inside a DLL, as the MSDN docs very clearly say:"If the dwThreadId parameter is zero or specifies the identifier of a thread created by a different process, the lpfn parameter must point to a hook procedure in a DLL." Indeed, the hook clearly has to be in a DLL, or how could the shell run the code during another application's message loop? The DLL installs the hook using its HINSTANCE to identify where the function pointer lives.
The main application runs starts the hooks, and pumps messages, again just following the instructions in the MSDN docs: "...the hooking application must continue to pump messages or it might block the normal functioning of the 64-bit processes."
Note that this is very niche application — hardly ever will you need to inject a DLL like this. Please, please, think twice about doing this. For many applications, it's not necessary to capture low-level events, although immersive applications that suppress the Start menu are a reasonable use-case. More importantly though, you very rarely need to capture input sent to other applications. Check before using this code that you really need to do this. For example, recording a macro can be done just by hooking the input to your own application's window.
main.cpp
#include <windows.h>
#include <tchar.h>
__declspec(dllimport) void (__stdcall runHook)(BOOL startOrStop);
__declspec(dllimport) LRESULT (CALLBACK hookProc)(int code, WPARAM wParam, LPARAM lParam);
int _tmain(int argc, _TCHAR* argv[])
{
runHook(true);
MSG Msg;
while(GetMessage(&Msg, NULL, 0, 0) > 0 && Msg.message != WM_QUIT) {
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
runHook(false);
return 0;
}
Dll.cpp
#include <assert.h>
#include <windows.h>
static HINSTANCE dllInst = 0;
static HHOOK hookSelf = 0;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
dllInst = (HINSTANCE)dllInst;
return TRUE;
}
__declspec(dllexport) LRESULT (CALLBACK hookProc)(int code, WPARAM wParam, LPARAM lParam)
{
if (code >= 0) {
UINT msgType = wParam;
KBDLLHOOKSTRUCT* msgInfo = (KBDLLHOOKSTRUCT*)lParam;
// The msgInfo contains the VK_CODE and flags.
}
return hookSelf ? CallNextHookEx(hookSelf, code, wParam, lParam) : 0;
}
__declspec(dllexport) void (__stdcall runHook)(BOOL startOrStop)
{
assert((bool)hookSelf != (bool)startOrStop);
if (startOrStop)
hookSelf = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, dllInst, 0);
else {
UnhookWindowsHookEx(hookSelf);
hookSelf = 0;
}
}
One way to do this is creating a TSR(Terminate and Stay Resident) program on Windows.
On Windows, a typical TSR program consists of the following components :
Creating and hiding the main window.
Registering hot keys.
The loop testing events.
Functions responding to hot keys.
Functions invoked periodically by timers.
Here is a good article with code-snippets and detailed explanations about writing TSRs on Windows.

Where do I add my actual program after I establish a Window using WinMain() and WindowProc()? (C++)

First of all, sorry for my ignorance of the window creation process. Today is actually the first day of my experimenting with it.
I started to code a text based game a few days ago and I have the main menu, and 3 or 4 different functions that control various things with text. I was then advised to look into Windows API and create a window for the program. I have created the window which can be seen here:
#include <Windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PWSTR nCmdLine, int nCmdShow)
{
const wchar_t CLASS_NAME[] = L"WindowClass";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.lpszClassName = CLASS_NAME;
wc.hInstance = hInstance;
RegisterClass(&wc);
HWND hwnd = CreateWindowEx( //This creats a new instance of a window
0,
CLASS_NAME,
L"MyFirstWindow",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
500,
500,
NULL,
NULL,
hInstance,
NULL);
if(hwnd == 0)
return 0;
ShowWindow(hwnd,nCmdShow);
nCmdShow = 1;
MSG msg = { };
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_DESTROY:PostQuitMessage(0); return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd,&ps);
FillRect(hdc,&ps.rcPaint,(HBRUSH)(COLOR_WINDOW+5));
EndPaint(hwnd, &ps);
}return 0;
case WM_CLOSE:
{
if(MessageBox(hwnd,L"Do you want to exit?",L"Exit",MB_OKCANCEL)==IDOK)
DestroyWindow(hwnd);
} return 0;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
This looks a bit messy, but you probably will not need it anyway.
So at this point I have my original program and this program that creates a window. My question is how, or even where, do I put my original program's code so that it can be incorporated into the window.
If you are reading this and thinking I'm a total moron for doing it this way, I'm open to ideas that are a lot simpler than what I'm doing right now.
Your code is the standard boilerplate for creating a window using c and win32 API functions. I recommend that you modify the message pump (it's the while loop in middle calling GetMessage). Instead do this:
Run an infinite loop
Peek a message
If the message is not there, execute your code
Else process messages including the quit message
Here's what the code should look like:
while (1)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
//Your game code
}
}
I also want to point, that while learning game programming using C and calling Win32 API is a worthy goal, you might want to look at XNA game studio.
The reason I am recommending it is because it is easier to learn and you can make much more interesting games faster. Here are a few links to get you started if you are interested.
http://joshua-w-wise78.livejournal.com/
http://www.krissteele.net/blogdetails.aspx?id=72
http://www.codeproject.com/KB/game/xna1.aspx
http://msdn.microsoft.com/en-us/library/bb203894.aspx
If your original program was a console app, that read input and printed output, then you will probably want to get input from your window to implement your game.
Instead of looking at it from the perspective of read user input from stdin then generate output to stdout, you have to think of it from the view of window messaging. So you need to process the WM_KEYDOWN messages, you can then use DrawText() to show the user input in your client area, or you could use a c++ RichEdit control. Once you process the WM_KEYDOWN messages you know what the user has pressed and then your program can do it's thing (maybe being triggered to process an accumalated buffer of characters whenever the WM_KEYDOWN key is equal to the enter key?) and write the output to your client area using DrawText() or send WM_KEYDOWN messages to your richedit window using SendMessage().
I think this is what you meant by a text based game, anyway, you just have to start thinking of doing everything by monitoring windows messages. Anything that the user does to your window, Windows will send a message to it to let it know.

How can I simulate key presses to any currently focused window?

I am trying to change the keys my keyboard sends to applications. I've already created a global hook and can prevent the keys I want, but I want to now send a new key in place. Here's my hook proc:
LRESULT __declspec (dllexport) HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
int ret;
if(nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
kbStruct = (KBDLLHOOKSTRUCT*)lParam;
printf("\nCaught [%x]", kbStruct->vkCode);
if(kbStruct->vkCode == VK_OEM_MINUS)
{
printf(" - oem minus!");
keybd_event(VK_DOWN, 72, KEYEVENTF_KEYUP, NULL);
return -1;
}
else if(kbStruct->vkCode == VK_OEM_PLUS)
{
printf(" - oem plus!");
keybd_event(VK_UP, 75, KEYEVENTF_KEYUP, NULL);
return -1;
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
I've tried using SendMessage and PostMessage with GetFocus() and GetForegroudWindow(), but can't figure out how to create the LPARAM for WM_KEYUP or WM_KEYDOWN. I also tried keybd_event(), which does simulate the keys (I know because this hook proc catches the simulated key presses), including 5 or 6 different scan codes, but nothing affects my foreground window.
I am basically trying to turn the zoom bar on my ms3200 into a scroll control, so I may even be sending the wrong keys (UP and DOWN).
Calling keybd_event is correct. If all you're doing is a key up, maybe the window processes the key down message instead. You really need to send a key down followed by a key up:
keybd_event(VK_UP, 75, 0, NULL);
keybd_event(VK_UP, 75, KEYEVENTF_KEYUP, NULL);
Or, better yet, send the key down when the OEM key goes down and a key up when the OEM key goes up. You can tell the down/up state by kbStruct->flags & LLKHF_UP.
You may wish to use SendInput, as keybd_event as has been superseded. The MSDN Magazine article C++ Q&A: Sending Keystrokes to Any App has a useful example.
You might want to try Control-UpArrow and Control-DownArrow instead of Up and Down. However this doesn't seem to work for all applications, and even on application where it does work, it may depend on where the focus is.

Resources