How to get the progress of a timer made with SetTimer() - c++

Is there any way to get the current progress of a timer, which is created by the SetTimer function?

Here's an implementation of Hans' comment. Clicking the button shows the time remaining until the next scheduled (expected) WM_TIMER message. By building in debug mode, I get a console to display my messages, since it's such a quick and easy (read: dirty) way of getting both a GUI and a console.
main.cpp
#include <windows.h>
#include <commctrl.h>
#include <stdio.h>
#include "resource.h"
HINSTANCE hInst;
DWORD tickCountInitial;
DWORD timerInterval = 10000;
DWORD nextTimerFired;
BOOL CALLBACK DlgMain(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_INITDIALOG:
{
tickCountInitial = GetTickCount();
SetTimer(hwndDlg, 666, timerInterval, NULL);
nextTimerFired = tickCountInitial + timerInterval;
}
return TRUE;
case WM_TIMER:
{
DWORD tickCountCurrent = GetTickCount();
printf("Ticks elapsed: %d\n", tickCountCurrent - tickCountInitial);
nextTimerFired = tickCountCurrent + timerInterval;
MessageBeep(MB_OK);
}
return 0;
case WM_CLOSE:
{
EndDialog(hwndDlg, 0);
}
return TRUE;
case WM_COMMAND:
{
switch(LOWORD(wParam))
{
case IDC_BUTTON1:
{
DWORD tickCountCurrent = GetTickCount();
printf("Ticks till next WM_TIMER message: %d\n", nextTimerFired - tickCountCurrent);
}
break;
}
}
return TRUE;
}
return FALSE;
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
hInst=hInstance;
InitCommonControls();
return DialogBox(hInst, MAKEINTRESOURCE(DLG_MAIN), NULL, (DLGPROC)DlgMain);
}
resource.h
#ifndef IDC_STATIC
#define IDC_STATIC (-1)
#endif
#define DLG_MAIN 100
#define IDC_BUTTON1 40000
resource.rc
// Generated by ResEdit 1.6.2
// Copyright (C) 2006-2014
// http://www.resedit.net
#include <windows.h>
#include <commctrl.h>
#include <richedit.h>
#include "resource.h"
//
// Dialog resources
//
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
DLG_MAIN DIALOG 0, 0, 186, 95
STYLE DS_3DLOOK | DS_CENTER | DS_MODALFRAME | DS_SHELLFONT | WS_CAPTION | WS_VISIBLE | WS_POPUP | WS_SYSMENU
CAPTION "Dialog"
FONT 8, "Ms Shell Dlg"
{
PUSHBUTTON "Check Remaining", IDC_BUTTON1, 41, 32, 104, 31, 0, WS_EX_LEFT
}
//
// Manifest resources
//
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
1 RT_MANIFEST ".\\manifest.xml"

Related

SetDlgItemInt doesn't change editbox of embedded resource

I've created in plain win32 c++ an options menu with an edit box using embedded resources. The edit box ID_EDIT_OPTIONS_BOX has a default value of 30. I can change to value in the edit box to eg 10. I've used the OK-button the place the code for reading and writing the editbox. After I click OK, this new value is stored in my variable INT testInt. But when i re-open the options menu, the edit box still reflects the default value as stored in the resource file.
The basic code I use is this:
testInt = GetDlgItemInt(hDlg, ID_EDIT_OPTIONS_BOX, NULL, FALSE);
SetDlgItemInt(hDlg, ID_EDIT_OPTIONS_BOX, testInt, FALSE);
Do I need to refresh the window or am I missing something really trivial? Below I've listed the full program code, resource header and file.
The program code:
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include "resource.h"
#define WIN32_LEAN_AND_MEAN
// Global variables
static TCHAR szWindowClass[] = _T("DesktopApp");
static TCHAR szTitle[] = _T("Windows Desktop Guided Tour Application");
HINSTANCE hInst;
int testInt;
// Forward declarations of functions included in this code module:
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK CheckOptionsProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow
)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDR_MENU);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, IDI_APPLICATION);
if (!RegisterClassEx(&wcex))
{
MessageBox(NULL,
_T("Call to RegisterClassEx failed!"),
_T("Windows Desktop Guided Tour"),
NULL);
return 1;
}
// Store instance handle in our global variable
hInst = hInstance;
HWND hWnd = CreateWindow(
szWindowClass,
szTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
500, 100,
NULL,
NULL,
hInstance,
NULL
);
if (!hWnd)
{
MessageBox(NULL,
_T("Call to CreateWindow failed!"),
_T("Windows Desktop Guided Tour"),
NULL);
return 1;
}
ShowWindow(hWnd,
nCmdShow);
UpdateWindow(hWnd);
// Main message loop:
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case ID_FILE_EXIT:
PostMessage(hWnd, WM_CLOSE, 0, 0);
break;
case ID_EDIT_OPTIONS:
DialogBox(hInst, MAKEINTRESOURCE(ID_EDIT_OPTIONS), hWnd, (DLGPROC)CheckOptionsProc);
break;
}
default:
return DefWindowProc(hWnd, message, wParam, lParam);
break;
}
return 0;
}
LRESULT CALLBACK CheckOptionsProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_COMMAND:
switch (LOWORD(wParam))
{
case ID_EDIT_OPTIONS_OK:
testInt = GetDlgItemInt(hDlg, ID_EDIT_OPTIONS_BOX, NULL, FALSE);
SetDlgItemInt(hDlg, ID_EDIT_OPTIONS_BOX, testInt, FALSE);
EndDialog(hDlg, IDOK);
break;
}
}
return 0;
}
The resource header
#define IDR_MENU 10
#define ID_FILE_EXIT 20
#define ID_EDIT_OPTIONS 30
#define ID_EDIT_OPTIONS_BOX 40
#define ID_EDIT_OPTIONS_OK 50
And resource file
#include "resource.h"
#include <windows.h>
IDR_MENU MENU
BEGIN
POPUP "&File"
BEGIN
MENUITEM "E&xit", ID_FILE_EXIT
END
POPUP "&Edit"
BEGIN
MENUITEM "&Options...", ID_EDIT_OPTIONS
END
END
ID_EDIT_OPTIONS DIALOGEX 0, 0, 260, 128
STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Options"
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
FONT 9, "SEGOE UI"
BEGIN
CONTROL "&OK", ID_EDIT_OPTIONS_OK, BUTTON, BS_DEFPUSHBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 145, 110, 50, 11
CONTROL "30", ID_EDIT_OPTIONS_BOX, EDIT, ES_RIGHT | WS_CHILD | WS_VISIBLE | WS_BORDER | WS_TABSTOP, 200, 13, 18, 10
END
Use SetDlgItemInt when dialog received WM_INITDIALOG message:
LRESULT CALLBACK CheckOptionsProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_INITDIALOG:
SetDlgItemInt(hDlg, ID_EDIT_OPTIONS_BOX, testInt, FALSE);
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case ID_EDIT_OPTIONS_OK:
testInt = GetDlgItemInt(hDlg, ID_EDIT_OPTIONS_BOX, NULL, FALSE);
EndDialog(hDlg, IDOK);
break;
}
}
return 0;
}
and remember to initialize testInt:
int testInt = 30;

Win32 Prevent being transparent the borders of the Window [duplicate]

This question already has an answer here:
Is it possible to create a winapi window with only borders
(1 answer)
Closed 2 years ago.
I am dealing with win32. I have created a window. What I want is a transparent window for clicked area but nontransparent for border. Additionaly with no title bar. It should seem like an empty rectangle. When I add the following code I, my whole window becomes transparent (borders are also tranparent.)
SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
SetLayeredWindowAttributes(hwnd, RGB(0, 0, 0), 75, LWA_ALPHA);
SetWindowLong(hwnd, GWL_STYLE, 0);
The output of my code by adding the above code is like following:
When opacity value is 255:
When opacity value is 75
As you can see that the borders also transparent. How can I prevent becoming transparent border, but obtain transparent clicked area like a rectange?
Thanks...
It looks like you want to make part of the window transparent.For this, you need to create two windows to complete.
Use SetWindowRgn to create a window with a hole
Use the WS_EX_LAYERED and WS_EX_TRANSPARENT style to place
another transparent window in the hole.
Like this:
The whole code:
// Test_transparent.cpp : Defines the entry point for the application.
//
#include "framework.h"
#include "Test_transparent.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
HWND hWnd;
HWND child;
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_TESTTRANSPARENT, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TESTTRANSPARENT));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TESTTRANSPARENT));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_TESTTRANSPARENT);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hWnd = CreateWindowEx(0, szWindowClass, L" ", WS_POPUP, 100, 100, 800, 600, NULL, NULL, hInst, 0);
child = CreateWindowEx(WS_EX_LAYERED, szWindowClass, szTitle, WS_POPUP | WS_VISIBLE | WS_CHILD, 300, 300, 200, 200, hWnd, NULL, hInst, 0);
SetLayeredWindowAttributes(child, 0, 50, LWA_ALPHA);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
RECT rect;
RECT rc;
COLORREF brColor;
static HRGN hRgnWnd;
static HRGN hRgnWnd1;
static HBRUSH hBr;
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
brColor = RGB(51, 143, 178);
hBr = CreateSolidBrush(brColor);
GetClientRect(hWnd, &rect);
rc.left = 200;
rc.top = 200;
rc.right = 400;
rc.bottom = 400;
hRgnWnd = CreateRectRgn(rect.left, rect.top, rect.right, rect.bottom);
hRgnWnd1 = CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
CombineRgn(hRgnWnd1, hRgnWnd1, hRgnWnd, RGN_XOR);
SetWindowRgn(hWnd, hRgnWnd1, true);
FillRect(hdc, &rect, hBr);
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
To get a borderless window, you need to comment the MENU code in the .rc file.
.rc cpp
//Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE resource.
//
#ifndef APSTUDIO_INVOKED
#include "targetver.h"
#endif
#define APSTUDIO_HIDDEN_SYMBOLS
#include "windows.h"
#undef APSTUDIO_HIDDEN_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE 9, 1
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_TESTTRANSPARENT ICON "Test_transparent.ico"
IDI_SMALL ICON "small.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Menu
//
//
//IDC_TESTTRANSPARENT MENU
//BEGIN
// POPUP "&File"
// BEGIN
// MENUITEM "E&xit", IDM_EXIT
// END
// POPUP "&Help"
// BEGIN
// MENUITEM "&About ...", IDM_ABOUT
// END
//END
/////////////////////////////////////////////////////////////////////////////
//
// Accelerator
//
IDC_TESTTRANSPARENT ACCELERATORS
BEGIN
"?", IDM_ABOUT, ASCII, ALT
"/", IDM_ABOUT, ASCII, ALT
END
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_ABOUTBOX DIALOGEX 0, 0, 170, 62
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "About Test_transparent"
FONT 8, "MS Shell Dlg"
BEGIN
ICON IDR_MAINFRAME,IDC_STATIC,14,14,21,20
LTEXT "Test_transparent, Version 1.0",IDC_STATIC,42,14,114,8,SS_NOPREFIX
LTEXT "Copyright (c) 2020",IDC_STATIC,42,26,114,8
DEFPUSHBUTTON "OK",IDOK,113,41,50,14,WS_GROUP
END
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO
BEGIN
IDD_ABOUTBOX, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 163
TOPMARGIN, 7
BOTTOMMARGIN, 55
END
END
#endif // APSTUDIO_INVOKED
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#ifndef APSTUDIO_INVOKED\r\n"
"#include ""targetver.h""\r\n"
"#endif\r\n"
"#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
"#include ""windows.h""\r\n"
"#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// String Table
//
STRINGTABLE
BEGIN
IDC_TESTTRANSPARENT "TESTTRANSPARENT"
IDS_APP_TITLE "Test_transparent"
END
#endif
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

Converting C++ dll injector into unicode

Okay so Ive Ran and tested the solution given on the website, which came with positive results.
Now I've converted this into a win32 unicode project without any compile errors or runtime errors(it even says its injected the dll). Without any noticeable errors everything seems fine other than the fact that the dll is not executing after injection.
Keep in mind the Dll does work if the Injectors character set is not set, but not if converted into unicode. Ive even converted the dll into unicode just to test and that works on the NON unicode Injector. With that in mind ive came to the conclusion that the problem lies in the converted Injector.
If anymore information is needed feel free to ask. You may also ask, why convert into unicode? its my personal preference. Since i did not write the code myself converting does help me learn the code.
I did Erase the 2nd function but that function was never called and was practically useless. it was the same function except with A different Variable Type. Conversion did not work prior to erasing.
Is there anything wrong with this code?
I think the problem is here in Injector.cpp
**Now I am thinking its the DLL. After changing kernel32.dll to something random i do receive an error through GetLastError() error 127 which was expected. But then the program of which was injected into crashes. which then means the dll was injected. ** So After thinking this through I tested without adding a dll into the equation, throws the same error along with the crash. seems like its injecting but its not injecting the dll. ** DLL_NAME is being loaded into the function. wcslen(DLL_NAME) is returning a value, along with RemoteString(is 0 with no dll loaded).
That being said I've included Dllmain.cpp
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include <Windows.h>
#include <string.h>
#include <stdio.h>
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
wchar_t* helloStr;
wchar_t buf[250];
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
helloStr = L"Hello";
wsprintf(buf, helloStr);
MessageBoxW(NULL, buf, NULL, NULL);
break;
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
helloStr = L"Goodbye";
wsprintf(buf, helloStr);
MessageBoxW(NULL, buf, NULL, NULL);
break;
}
return TRUE;
}
Injector.cpp
#include "stdafx.h"
#include <windows.h>
#include <tlhelp32.h>
#include <shlwapi.h>
#include <conio.h>
#include <stdio.h>
#include <iostream>
#include "Resource.h"
Injector::Injector(void)
{
}
Injector::~Injector(void)
{
}
#define CREATE_THREAD_ACCESS (PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ)
bool Injector::Inject(wchar_t* procName, wchar_t* DLL_NAME)
{
DWORD pID = GetTargetThreadIDFromProcName(procName);
HANDLE Proc = 0;
HMODULE hLib = 0;
wchar_t buf[50] = { 0 };
LPVOID RemoteString, LoadLibAddy;
if (!pID)
return false;
Proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pID);
if (!Proc)
{
swprintf_s(buf, L"OpenProcess() failed: %d", GetLastError());
MessageBoxW(NULL, buf, L"Loader", MB_OK);
wprintf(buf);
return false;
}
LoadLibAddy = (LPVOID)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW");
// Allocate space in the process for our DLL
RemoteString = (LPVOID)VirtualAllocEx(Proc, NULL, wcslen(DLL_NAME), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
// Write the string name of our DLL in the memory allocated
WriteProcessMemory(Proc, (LPVOID)RemoteString, DLL_NAME, wcslen(DLL_NAME), NULL);
// Load our DLL
CreateRemoteThread(Proc, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibAddy, (LPVOID)RemoteString, NULL, NULL);
CloseHandle(Proc);
return true;
}
DWORD Injector::GetTargetThreadIDFromProcName(wchar_t* ProcName)
{
PROCESSENTRY32 pe;
HANDLE thSnapShot;
BOOL retval = false;
thSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (thSnapShot == INVALID_HANDLE_VALUE)
{
MessageBoxW(NULL, L"Error: Unable to create toolhelp snapshot!", L"2MLoader", MB_OK);
return false;
}
pe.dwSize = sizeof(PROCESSENTRY32);
retval = Process32First(thSnapShot, &pe);
while (retval)
{
if (!wcscmp(pe.szExeFile, ProcName))
{
return pe.th32ProcessID;
}
retval = Process32Next(thSnapShot, &pe);
}
return 0;
}
Resource.h
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 130
#define _APS_NEXT_RESOURCE_VALUE 129
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 110
#endif
#endif
#pragma once
#include <Windows.h>
class Injector
{
public:
Injector(void);
~Injector(void);
bool Inject(wchar_t* procName, wchar_t* DLL_NAME);
private:
DWORD GetTargetThreadIDFromProcName(wchar_t * ProcName);
};
Main.cpp
// DLL_Injector_WIN32.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "DLL_Injector_WIN32.h"
#include <Commdlg.h>
#include <iostream>
#include <Windows.h>
#include "Resource.h"
#define MAX_LOADSTRING 100
Injector* injector = new Injector();
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
wchar_t szFile[MAX_PATH];
LPTSTR PROC_NAME = new TCHAR[1024];
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
BOOL FileOpen(HWND hwnd);
int start(wchar_t* DLL_PATH, wchar_t* PROC_NAME);
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_DLL_INJECTOR_WIN32, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_DLL_INJECTOR_WIN32));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_DLL_INJECTOR_WIN32));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_DLL_INJECTOR_WIN32);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindowEx(
WS_EX_CLIENTEDGE,
szWindowClass,
szTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 350, 100,
NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_CREATE:
CreateWindowEx(
WS_EX_CLIENTEDGE,
L"BUTTON",
L"Inject",
WS_CHILD | WS_VISIBLE | WS_EX_CLIENTEDGE,
280, 10, 45, 25,
hWnd, (HMENU)IDC_INJECT, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
CreateWindowEx(
WS_EX_CLIENTEDGE,
L"BUTTON",
L"DLL",
WS_CHILD | WS_VISIBLE | WS_EX_CLIENTEDGE,
240, 10, 35, 25,
hWnd, (HMENU)IDC_DLL, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
CreateWindowEx(
WS_EX_CLIENTEDGE,
L"EDIT",
L"",
WS_CHILD | WS_VISIBLE | WS_EX_CLIENTEDGE | ES_AUTOHSCROLL,
65, 10, 170, 25,
hWnd, (HMENU)IDC_PROCESS, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
CreateWindowEx(
0,
L"STATIC",
L"Process",
WS_CHILD | WS_VISIBLE,
5, 10, 55, 25,
hWnd, (HMENU)NULL, ((LPCREATESTRUCT)lParam)->hInstance, NULL);
break;
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDC_DLL:
{
FileOpen(hWnd);
// MessageBox(NULL, szFile, L"TEST", NULL);
}
break;
case IDC_INJECT:
{
GetDlgItemText(hWnd, IDC_PROCESS, PROC_NAME, 1024);
start(szFile, PROC_NAME);
}
break;
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
BOOL FileOpen(HWND hwnd)
{
OPENFILENAME ofn;
HANDLE hf;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"DLL\0*.dll\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileNameW(&ofn) == TRUE)
{
//CheckDlgButton(hwnd, IDC_PASS_LIST, BST_UNCHECKED);
hf = CreateFile(ofn.lpstrFile,
GENERIC_READ,
FILE_SHARE_READ,
(LPSECURITY_ATTRIBUTES)NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE)NULL);
return TRUE;
if (hf == (HANDLE)-1)
{
MessageBox(NULL, L"Could not open this file", L"File I/O Error", MB_ICONSTOP);
return FALSE;
}
}
else
{
return FALSE;
}
}
int start(wchar_t* DLL_PATH, wchar_t* PROC_NAME)
{
WCHAR dllDir[MAX_PATH];
wcscpy_s(dllDir, MAX_PATH, DLL_PATH);
//MessageBox(NULL, dllDir, L"DLL path: ", MB_ICONSTOP);
//MessageBox(NULL, PROC_NAME, L"Process: ", MB_ICONSTOP);
if (injector->Inject(PROC_NAME, dllDir)){
MessageBox(NULL, L"DLL injected!", L"DLL injected!", MB_ICONSTOP);
}
else {
MessageBox(NULL, L"Failed to inject the dll...", L"File I/O Error", MB_ICONSTOP);
}
return 0;
}
Turns out WriteProcessMemory wanted DLL_NAME to be a char. converted wchar_t* to char in a new variable and now i have no problems.

Tooltip Coloring doesnot work

I am newbie in c++ win32 Programming and I am using visual studio 2013 on Windows 7 X64 SP1.
I have used this code in link below to create tooltip for a button in DialogBox and successfully it worked.
Tooltip for button
but when I want to change the background color or foreground color , it does not work and it shows the default colors.
SendMessage(hwndTip, TTM_SETTIPBKCOLOR, 0xFF326FD8, 0);
//SendMessage(hwndTip, TTM_SETTIPBKCOLOR, (WPARAM)CreateSolidBrush(RGB(255,255, 255), 0);
SendMessage(hwndTip, TTM_SETTIPTEXTCOLOR, (WPARAM)CreateSolidBrush(RGB(255,255, 255)), 0);
Because in this link :
http://msdn.microsoft.com/en-us/library/windows/desktop/bb760411%28v=vs.85%29.aspx
the MSDN said that "When visual styles are enabled, this message has no effect." so I changed the
HWND hwndTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL,
WS_POPUP | TTS_ALWAYSTIP | TTS_BALLOON |TTS_USEVISUALSTYLE,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
hDlg, NULL,
hInst, NULL);
to :
HWND hwndTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL,
WS_POPUP | TTS_ALWAYSTIP | TTS_BALLOON,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
hDlg, NULL,
hInst, NULL);
but without any success.
also I have used :
#pragma comment(linker, \
"\"/manifestdependency:type='Win32' "\
"name='Microsoft.Windows.Common-Controls' "\
"version='6.0.0.0' "\
"processorArchitecture='*' "\
"publicKeyToken='6595b64144ccf1df' "\
"language='*'\"")
in my code so I removed it to see if tooltip coloring works but the tooltip did not appeared at all !
what is the problem ?
Thanks.
Update 1 :
Here is my full source code , hope to solve the problem :
Main.cpp :
#include <Windows.h>
#include <stdlib.h>
#include <tchar.h>
#include <memory>
#include <malloc.h>
#include "resource.h"
#include <CommCtrl.h>
#include <Uxtheme.h>
HINSTANCE hInst;
BOOL InitInstance(HINSTANCE, int);
INT_PTR CALLBACK MainWin(HWND, UINT, WPARAM, LPARAM);
#pragma comment(linker, \
"\"/manifestdependency:type='Win32' "\
"name='Microsoft.Windows.Common-Controls' "\
"version='6.0.0.0' "\
"processorArchitecture='*' "\
"publicKeyToken='6595b64144ccf1df' "\
"language='*'\"")
#pragma comment(lib, "ComCtl32.lib")
#pragma comment(lib,"UxTheme.lib")
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,_In_opt_ HINSTANCE hPrevInstance,_In_ LPTSTR lpCmdLine,_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
MSG msg;
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
while (GetMessage(&msg, NULL, 0, 0)>0)
{
if (!IsDialogMessage(msg.hwnd,&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int)msg.wParam;
}
HWND CreateToolTip(int toolID, HWND hDlg, HINSTANCE hInst, PTSTR pszText)
{
if (!toolID || !hDlg || !pszText)
{
return NULL;
}
HWND hwndTool = GetDlgItem(hDlg, toolID);
if (!hwndTool)
{
return NULL;
}
HWND hwndTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL,
WS_POPUP | TTS_ALWAYSTIP | TTS_BALLOON |TTS_USEVISUALSTYLE,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
hDlg, NULL,
hInst, NULL);
if (!hwndTip)
{
return NULL;
}
TOOLINFO toolInfo = { 0 };
toolInfo.cbSize = sizeof(toolInfo);
toolInfo.hwnd = hDlg;
toolInfo.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
toolInfo.uId = (UINT_PTR)hwndTool;
toolInfo.lpszText = pszText;
if (!SendMessage(hwndTip, TTM_ADDTOOL, 0, (LPARAM)&toolInfo))
{
DestroyWindow(hwndTip);
return NULL;
}
SendMessage(hwndTip, TTM_SETTIPBKCOLOR, 0xFF326FD8, 0);
return hwndTip;
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hWnd = CreateDialogParam(hInstance, MAKEINTRESOURCE(IDD_MainDlg), NULL, MainWin, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
SetWindowTheme(hWnd, L"", L"");
return TRUE;
}
INT_PTR CALLBACK MainWin(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
{
CreateToolTip(IDC_TestBtn, hDlg, hInst, L"TESTTOOLTIP");
return (INT_PTR)TRUE;
}
break;
case WM_CLOSE:
DestroyWindow(hDlg);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_COMMAND:
if (LOWORD(wParam) == IDC_TestBtn)
{
MessageBox(NULL, L"TEST", L"TEST", MB_OK);
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
}
resource.h :
#define IDD_MainDlg 103
#define IDC_TestBtn 104
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 106
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1006
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
resource script for resource.rc :
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO
BEGIN
IDD_MainDlg, DIALOG
BEGIN
END
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_MainDlg DIALOGEX 0, 0, 149, 75
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
EXSTYLE WS_EX_TOOLWINDOW
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
PUSHBUTTON "testbtn",IDC_TestBtn,41,12,57,49
END
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////

C++: Getting information from a Listbox with LB_GETCURSEL and LB_GETTEXT

I'm creating a Listbox with a list of foders. I want to show the name of the folder the user double click. To do so, I have written:
...
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
char Temp[_MAX_DIR]
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Analizar las selecciones de menĂº:
switch (wmId)
{
case ID_LIST:
SelIndex = SendMessage(hList, LB_GETCURSEL, 0, 0L);
SendMessage(hList, LB_GETTEXT, (WPARAM)(int)(SelIndex), (LPARAM)(LPCTSTR)(Temp));
printf("The folder is: %s\n", Temp);
...
The most relevant lines are:
SelIndex = SendMessage(hList, LB_GETCURSEL, 0, 0L);
SendMessage(hList, LB_GETTEXT, (WPARAM)(int)(SelIndex), (LPARAM)(LPCTSTR)(Temp));
With the first one I should get the line of the list box the user have clicked, and with the second one I should store into Temp the text that appears in the clicked line. But I get nothing, what am I doing wrong??
Thank you
/////////////////Combining the answers of some users, a script that works is like follows:
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Analizar las selecciones de menĂº:
if (wmEvent == LBN_DBLCLK)
{
if(wmId == ID_LIST)
{
SelIndex = SendMessage(hList, LB_GETCURSEL, 0, 0L);
printf("The index is %d\n", SelIndex);
len = SendMessage(hList, LB_GETTEXT, (WPARAM)(int)(SelIndex), (LPARAM)(LPCTSTR)(Temp));
printf("Lenght is %d\n", len);
printf("The folder is: %s\n",Temp);
Your program has some problems. First of all you seem to be doing a lot more casting than you need to. That's always a worry. You also neglect basic error checking. For instance:
SelIndex = SendMessage(hList, LB_GETCURSEL, 0, 0L);
You assign to SelIndex but don't check for errors. The documentation tells you that in the event of error, LB_ERR is returned. You must check for that.
Next up is:
SendMessage(hList, LB_GETTEXT, (WPARAM)(int)(SelIndex), (LPARAM)(LPCTSTR)(Temp));
The casting seems extreme. You could write it like this:
SendMessage(hList, LB_GETTEXT, SelIndex, (LPARAM)Temp);
You should also capture the return value and check for errors. Again, you must consult the documentation carefully.
Now, the most likely cause of problems is that you are compiling a Unicode project. And so are expected to supply a buffer of wide characters. So change the declaration of Temp like so:
wchar_t Temp[_MAX_DIR];
Another possible problem is that you are expected to supply a buffer of sufficient length for the string, and the null-terminator. Again, the documentation makes this clear. Use LB_GETTEXTLEN to find out how large a buffer you need.
Note: I was assuming that your code does actually execute. But the other answers suggest that your code may not execute. In which case that's the first thing to sort out. Confirming facts like that is a basic part of debugging and is something that you must learn to do. So, irrespective of what fixes the problem, the best advice I can give you is to try learn how to diagnose and describe a problem better. Doing that makes it much easier for you to narrow the problem down and so find the solution. In other words here, the main problem you had, in my view, was that you had not fully identified your problem.
A couple of more points in addition to what #DavidHeffernan mentioned in his answer:
a) the logic for case ID_LIST should be within if (wmEvent == LBN_DBLCLK)
b) printf() will not do anything in a windows application, try OutputDebugString() instead for debug builds or a MessageBox()
I'm creating a Listbox with a list of foders.I want to show the name of the folder the user double click.
You can use simple list box to do that, or you can use DlgDirList function to do that-all you need to do is to pass DDL_DIRECTORY as the last parameter. This function always adds file names as well to the list box, so you will need to find a way to filter them on your own. Also, notice that it provides HWND of the static control that will display the name of the folder, so this might be useful to you ( this parameter can be NULL if you do not wish to use static control ).
NOTE ABOUT DlgDirList:
Directory names have square brackets like this : [directory].
But I get nothing, what am I doing wrong??
You get some result. You can not just appear here and say "I get nothing". Explain what is the behavior you get, and what is the one you expected.
THE SOLUTION:
After looking at your code, I can see what could be wrong-you haven't handled the LBN_DBLCLK notification message.
Also. note that your list box has to have LBS_NOTIFY style in order to send notification messages to your parent window.
If you provide more detailed explanation of the problem community will have better chance to help you. So far this is the only relevant problem I see in your code.
RESOURCES ( these should help you to solve your problem ):
Microsoft has two good examples for populating list boxes and extracting data from them.
If you are OK with allowing the user to see both files and directories then you can use this example, just do not forget the DDL_DIRECTORY flag I mentioned above.
If you only want directories in your list box than you will find this example useful.
EXAMPLE:
To help you with those examples, I have made a demo application that demonstrates both ways.
This code shows you how to populate list box with your data and how to extract strings on double clicks.
Just go to File and choose one of two options to see the demonstration.
First option in the menu lists the data of the player when you double click the item in the edit control ( I have modified Microsoft's second example from above ), while the second option lists files in your current directory and deletes the file you double click on.
In my opinion, the solution you seek is best illustrated in the dialog procedure ListBoxExampleProc. Pay attention how the items are added ( WM_INITDIALOG handler ) and how I get the string from items on double click ( in WM_COMMAND handler find and study case IDC_LIST1 ).
You will need to implement your desired behavior on your own ( obtaining the directory names and populating the list box properly ) since I had no time to do that for you-Christnmas has passed so no gifts for you this time :)
Hopefully this will help you. If you have further questions leave a comment and I will respond.
Best regards.
INSTRUCTIONS:
Create default Win32 project in Visual Studio. Name it "list box test".
Then all you have to do is to replace the original text of the following files with my code:
stdafx.h:
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
#include <tchar.h>
#include <Strsafe.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
Resource.h:
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by list box test.rc
//
#define IDC_MYICON 2
#define IDD_LISTBOXTEST_DIALOG 102
#define IDS_APP_TITLE 103
#define IDD_ABOUTBOX 103
#define IDM_ABOUT 104
#define IDM_EXIT 105
#define IDI_LISTBOXTEST 107
#define IDI_SMALL 108
#define IDC_LISTBOXTEST 109
#define IDR_MAINFRAME 128
#define IDD_DIALOG1 129
#define IDD_DIALOG2 130
#define IDC_LIST1 1000
#define IDC_EDIT1 1002
#define IDS_PATHTOFILL 1003
#define ID_FILE_SIMPLELISTBOX 32771
#define ID_FILE_DIRECTORYLISTBOX 32772
#define IDC_STATIC -1
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 131
#define _APS_NEXT_COMMAND_VALUE 32773
#define _APS_NEXT_CONTROL_VALUE 1004
#define _APS_NEXT_SYMED_VALUE 110
#endif
#endif
list box test.rc:
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#ifndef APSTUDIO_INVOKED
#include "targetver.h"
#endif
#define APSTUDIO_HIDDEN_SYMBOLS
#include "windows.h"
#undef APSTUDIO_HIDDEN_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_LISTBOXTEST ICON "list box test.ico"
IDI_SMALL ICON "small.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Menu
//
IDC_LISTBOXTEST MENU
BEGIN
POPUP "&File"
BEGIN
MENUITEM "Simple list box", ID_FILE_SIMPLELISTBOX
MENUITEM "Directory list box", ID_FILE_DIRECTORYLISTBOX
MENUITEM "E&xit", IDM_EXIT
END
POPUP "&Help"
BEGIN
MENUITEM "&About ...", IDM_ABOUT
END
END
/////////////////////////////////////////////////////////////////////////////
//
// Accelerator
//
IDC_LISTBOXTEST ACCELERATORS
BEGIN
"?", IDM_ABOUT, ASCII, ALT
"/", IDM_ABOUT, ASCII, ALT
END
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_ABOUTBOX DIALOGEX 0, 0, 170, 62
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "About list box test"
FONT 8, "MS Shell Dlg", 0, 0, 0x1
BEGIN
ICON 128,IDC_STATIC,14,14,21,20
LTEXT "list box test, Version 1.0",IDC_STATIC,42,14,114,8,SS_NOPREFIX
LTEXT "Copyright (C) 2014",IDC_STATIC,42,26,114,8
DEFPUSHBUTTON "OK",IDOK,113,41,50,14,WS_GROUP
END
IDD_DIALOG1 DIALOGEX 0, 0, 335, 180
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Dialog"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
DEFPUSHBUTTON "OK",IDOK,205,159,50,14
PUSHBUTTON "Cancel",IDCANCEL,278,159,50,14
LISTBOX IDC_LIST1,23,14,99,140,LBS_SORT | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
EDITTEXT IDC_EDIT1,140,34,179,22,ES_MULTILINE | ES_AUTOHSCROLL | ES_READONLY
END
IDD_DIALOG2 DIALOGEX 0, 0, 316, 180
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Dialog"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
DEFPUSHBUTTON "OK",IDOK,205,159,50,14
PUSHBUTTON "Cancel",IDCANCEL,259,159,50,14
LISTBOX IDC_LIST1,24,17,173,141,LBS_SORT | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
LTEXT "",IDS_PATHTOFILL,209,31,90,18,0,WS_EX_CLIENTEDGE
CTEXT "Current working directory:",IDC_STATIC,209,18,89,9,SS_ENDELLIPSIS
END
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO
BEGIN
IDD_ABOUTBOX, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 163
TOPMARGIN, 7
BOTTOMMARGIN, 55
END
IDD_DIALOG1, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 328
TOPMARGIN, 7
BOTTOMMARGIN, 173
END
IDD_DIALOG2, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 309
TOPMARGIN, 7
BOTTOMMARGIN, 173
END
END
#endif // APSTUDIO_INVOKED
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#ifndef APSTUDIO_INVOKED\r\n"
"#include ""targetver.h""\r\n"
"#endif\r\n"
"#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
"#include ""windows.h""\r\n"
"#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// String Table
//
STRINGTABLE
BEGIN
IDS_APP_TITLE "list box test"
IDC_LISTBOXTEST "LISTBOXTEST"
END
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
list box test.cpp:
// list box test.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "list box test.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
//*********** Variables required for the second list box example
typedef struct
{
TCHAR achName[MAX_PATH];
TCHAR achPosition[12];
int nGamesPlayed;
int nGoalsScored;
} Player;
Player Roster[] =
{
{TEXT("Haas, Jonathan"), TEXT("Midfield"), 18, 4 },
{TEXT("Pai, Jyothi"), TEXT("Forward"), 36, 12 },
{TEXT("Hanif, Kerim"), TEXT("Back"), 26, 0 },
{TEXT("Anderberg, Michael"), TEXT("Back"), 24, 2 },
{TEXT("Jelitto, Jacek"), TEXT("Midfield"), 26, 3 },
{TEXT("Raposo, Rui"), TEXT("Back"), 24, 3},
{TEXT("Joseph, Brad"), TEXT("Forward"), 13, 3 },
{TEXT("Bouchard, Thomas"), TEXT("Forward"), 28, 5 },
{TEXT("Salmre, Ivo "), TEXT("Midfield"), 27, 7 },
{TEXT("Camp, David"), TEXT("Midfield"), 22, 3 },
{TEXT("Kohl, Franz"), TEXT("Goalkeeper"), 17, 0 },
};
//**************************************************
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_LISTBOXTEST, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_LISTBOXTEST));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage are only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this function
// so that the application will get 'well formed' small icons associated
// with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_LISTBOXTEST));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_LISTBOXTEST);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//************ Modified second example of the list box *****************//
//*********** from http://msdn.microsoft.com/en-us/library/windows/desktop/hh298365%28v=vs.85%29.aspx
INT_PTR CALLBACK ListBoxExampleProc(HWND hDlg, UINT message,
WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
{
// Add items to list.
HWND hwndList = GetDlgItem(hDlg, IDC_LIST1);
for (int i = 0; i < ARRAYSIZE(Roster); i++)
{
int pos = (int)SendMessage(hwndList, LB_ADDSTRING, 0,
(LPARAM) Roster[i].achName);
// we do not need the rest from Microsoft's example
}
// Set input focus to the list box.
SetFocus(hwndList);
return TRUE;
}
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
EndDialog(hDlg, LOWORD(wParam));
return TRUE;
case IDC_LIST1:
{
switch (HIWORD(wParam))
{
case LBN_DBLCLK:
{
HWND hwndList = GetDlgItem(hDlg, IDC_LIST1);
// Get selected index.
int lbItem = (int)SendMessage(hwndList, LB_GETCURSEL, 0, 0);
// display item's text
TCHAR buff[MAX_PATH];
SendMessage(hwndList, LB_GETTEXT, lbItem, (LPARAM)buff);
SetDlgItemText(hDlg, IDC_EDIT1, buff);
return TRUE;
}
}
}
return TRUE;
}
}
return FALSE;
}
//************ Modified first example of the list box **************//
//*********** from http://msdn.microsoft.com/en-us/library/windows/desktop/hh298372%28v=vs.85%29.aspx
INT_PTR CALLBACK DlgDelFileProc(HWND hDlg, UINT message,
UINT wParam, LONG lParam)
{
PTSTR pszCurDir;
PTSTR pszFileToDelete;
int iLBItem;
int cStringsRemaining;
int iRet;
TCHAR achBuffer[MAX_PATH];
TCHAR achTemp[MAX_PATH];
BOOL fResult;
switch (message)
{
case WM_INITDIALOG:
// Initialize the list box by filling it with files from
// the current directory.
pszCurDir = achBuffer;
GetCurrentDirectory(MAX_PATH, pszCurDir);
DlgDirList(hDlg, pszCurDir, IDC_LIST1, IDS_PATHTOFILL, DDL_DIRECTORY);
SetFocus(GetDlgItem(hDlg, IDC_LIST1));
return FALSE;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDC_LIST1:
if( HIWORD(wParam) == LBN_DBLCLK )
{
// When the user double clicks the item,
// first retrieve the selected file.
pszFileToDelete = achBuffer;
DlgDirSelectEx(hDlg, pszFileToDelete, MAX_PATH, IDC_LIST1);
// Make sure the user really wants to delete the file.
achTemp[MAX_PATH];
StringCbPrintf (achTemp, ARRAYSIZE(achTemp),
TEXT("Are you sure you want to delete %s?"),
pszFileToDelete);
iRet = MessageBox(hDlg, achTemp, L"Deleting Files",
MB_YESNO | MB_ICONEXCLAMATION);
if (iRet == IDNO)
return TRUE;
// Delete the file.
fResult = DeleteFile(pszFileToDelete);
if (!fResult)
{
MessageBox(hDlg, L"Could not delete file.", NULL, MB_OK);
}
else // Remove the filename from the list box.
{
// Get the selected item.
iLBItem = SendMessage(GetDlgItem(hDlg, IDC_LIST1),
LB_GETCURSEL, 0, 0);
// Delete the selected item.
cStringsRemaining = SendMessage(GetDlgItem(hDlg, IDC_LIST1),
LB_DELETESTRING, iLBItem, 0);
// If this is not the last item, set the selection to
// the item immediately following the one just deleted.
// Otherwise, set the selection to the last item.
if (cStringsRemaining > iLBItem)
{
SendMessage(GetDlgItem(hDlg, IDC_LIST1), LB_SETCURSEL,
iLBItem, 0);
}
else
{
SendMessage(GetDlgItem(hDlg, IDC_LIST1), LB_SETCURSEL,
cStringsRemaining, 0);
}
}
}
break;
case IDOK:
case IDCANCEL:
// Destroy the dialog box.
EndDialog(hDlg, TRUE);
return TRUE;
default:
return FALSE;
}
default:
return FALSE;
}
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case ID_FILE_SIMPLELISTBOX:
DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG1), hWnd, ListBoxExampleProc);
break;
case ID_FILE_DIRECTORYLISTBOX:
DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG2), hWnd, DlgDelFileProc);
break;
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
Actually what I get is first letter of selected listbox element.
//hEdit 2 - edit widnow, hWndList - listbox window
char z[20] = {"hhhhh"};
LRESULT SelIndex;
SelIndex = SendMessage(hWndList, LB_GETCURSEL, 0, 0L);
tmp_str = std::to_string(SelIndex);
SendMessage(hWndList, LB_GETTEXT, SelIndex, (LPARAM)z);
SetWindowTextA(hEdit2, z);