Converting C++ dll injector into unicode - c++

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.

Related

WM_HOVER not working with WinAPI ListView

I have a ListView drawing to the screen. Now, I am trying to have a function called when the user hovers over the items. I am trying to use WM_HOVER right now because it seems the most straight foward; however, it doesn't seem to be working. I got WM_CLICK to work fine, but not for the hovering.
Will WM_HOVER do what I need it to, or should I be looking into something else such as TrackMouseEvent()?
Here is some example code. Really the only pertinent part, I believe, are the lines in the WndProc() following case WM_HOVER:
//libraries
#pragma comment ("lib", "Comctl32.lib")
#pragma comment ("lib", "d2d1.lib")
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files
#include <windows.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#include <vector>
#include <string>
#include <dwrite.h>
#include <d2d1.h>
#include <commctrl.h>
#include <strsafe.h>
#define IDS_APP_TITLE 103
#define IDR_MAINFRAME 128
#define IDD_PRACTICE_DIALOG 102
#define IDD_ABOUTBOX 103
#define IDM_EXIT 105
#define IDI_PRACTICE 107
#define IDI_SMALL 108
#define IDC_PRACTICE 109
#define IDC_MYICON 2
#ifndef IDC_STATIC
#define IDC_STATIC -1
#endif
#define MAX_LOADSTRING 100
#define PROJECT_LIST_VIEW 110
BOOL mouseTracking = false;
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
std::vector<std::string> stringsVector = { "String1", "String2", "String3" };
//D2D1 pointers
ID2D1Factory* m_pD2DFactory;
ID2D1DCRenderTarget* m_pRenderTarget;
ID2D1SolidColorBrush* m_pBlackBrush;
//dimension variables
int w, h;
RECT rc;
HWND listViewHandle;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow);
HRESULT CreateDeviceResources(HWND hwnd, HDC hdc);
bool onRender(HWND hwnd, PAINTSTRUCT* ps);
///////////////////
//Function to insert the items into the list view
//////////////////
BOOL InsertListViewItems(HWND hWndListView, int cItems);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_PRACTICE, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_PRACTICE));
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;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
switch (message)
{
case WM_CREATE:
//Create the List View Control
listViewHandle = CreateWindow(WC_LISTVIEW, L"", WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_EDITLABELS, 100, 100, 500, 500, hWnd, (HMENU)PROJECT_LIST_VIEW, hInst, NULL);
InsertListViewItems(listViewHandle, stringsVector.size());
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_PAINT:
{
HDC hdc = BeginPaint(hWnd, &ps);
onRender(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
}
case WM_SIZE:
{
if (m_pRenderTarget)
{
m_pRenderTarget->Release();
m_pRenderTarget = nullptr;
}
break;
}
////////////////////////////////////////////
//
// HERE ARE THE MOUSE MOVE CASES
//
/////////////////////////////////////////////
case WM_MOUSEHOVER:
{
OutputDebugStringA("HOVER\n");
mouseTracking = FALSE;
break;
}
case WM_MOUSEMOVE:
if (!mouseTracking)
{
// start tracking if we aren't already
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_HOVER | TME_LEAVE;
tme.hwndTrack = listViewHandle; //This is the handle to the ListView window
tme.dwHoverTime = HOVER_DEFAULT;
mouseTracking = TrackMouseEvent(&tme);
}
break;
case WM_MOUSELEAVE:
mouseTracking = FALSE;
break;
case WM_NOTIFY:
{
NMLVDISPINFO* plvdi;
switch (((LPNMHDR)lParam)->code)
{
case NM_CLICK:
OutputDebugStringA("CLICK\n");
break;
case LVN_GETDISPINFO:
{
////////////////////
//This is the callback that sets the pszText attribute of the items
////////////////////
plvdi = (NMLVDISPINFO*)lParam;
const char* inString = stringsVector[plvdi->item.iItem].c_str();
size_t size = strlen(inString) + 1;
wchar_t* outString = new wchar_t[size];
size_t outSize;
mbstowcs_s(&outSize, outString, size, inString, size - 1);
LPWSTR ptr = outString;
StringCchCopy(plvdi->item.pszText, plvdi->item.cchTextMax, outString);
delete[] outString;
break;
}
}
break;
}
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
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_PRACTICE));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_PRACTICE);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
D2D1CreateFactory(
D2D1_FACTORY_TYPE_SINGLE_THREADED,
&m_pD2DFactory
);
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//////////////////
//Function to insert the items into the list view
//////////////////
BOOL InsertListViewItems(HWND hWndListView, int cItems)
{
LVCOLUMN lvc;
lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
// Initialize LVITEM members that are common to all items.
// Initialize LVITEM members that are different for each item.
lvc.iSubItem = 0;
lvc.pszText = (LPWSTR)L"test";
lvc.cx = 200;
// Insert items into the list.
if (ListView_InsertColumn(hWndListView, 0, &lvc) == -1)
return FALSE;
LVITEM lvI;
// Initialize LVITEM members that are common to all items.
lvI.pszText = LPSTR_TEXTCALLBACK; //This should send an LVN_GETDISPINFO message
lvI.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_STATE;
lvI.stateMask = 0;
lvI.iSubItem = 0;
lvI.state = 0;
// Initialize LVITEM members that are different for each item.
for (int index = 0; index < cItems; index++)
{
lvI.iItem = index;
lvI.iImage = index;
// Insert items into the list.
if (ListView_InsertItem(hWndListView, &lvI) == -1)
return FALSE;
}
return TRUE;
}
HRESULT CreateDeviceResources(HWND hwnd, HDC hdc)
{
HRESULT hr = S_OK;
if (!m_pRenderTarget) { //If m_pRenderTarget changes size
// Create a DC render target.
D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
D2D1_RENDER_TARGET_TYPE_DEFAULT,
D2D1::PixelFormat(
DXGI_FORMAT_B8G8R8A8_UNORM,
D2D1_ALPHA_MODE_IGNORE),
0,
0,
D2D1_RENDER_TARGET_USAGE_NONE,
D2D1_FEATURE_LEVEL_DEFAULT
);
hr = m_pD2DFactory->CreateDCRenderTarget(&props, &m_pRenderTarget);
GetClientRect(hwnd, &rc);
if (SUCCEEDED(hr))
hr = m_pRenderTarget->BindDC(hdc, &rc);
D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
w = size.width;
h = size.height;
if (SUCCEEDED(hr))
{//position objects
// Create a black brush
hr = m_pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &m_pBlackBrush);
}
}
return hr;
}
bool onRender(HWND hwnd, PAINTSTRUCT* ps)
{
HDC hdc = ps->hdc;
HRESULT hr;
hr = CreateDeviceResources(hwnd, hdc);
if (SUCCEEDED(hr))
{
m_pRenderTarget->BeginDraw();
m_pRenderTarget->SetTransform(D2D1::IdentityMatrix());
m_pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
hr = m_pRenderTarget->EndDraw();
}
SetWindowPos(listViewHandle, HWND_TOP, w * .1, h * .1, w * .3, h * .3, SWP_SHOWWINDOW);
SendMessage(listViewHandle, LVM_SETCOLUMNWIDTH, 0, w * .2);
if(SUCCEEDED(hr))
return true;
return false;
}
As dxiv said, If you need to handle NM_HOVER message, you need to add LVS_EX_TRACKSELECT style:
ListView_SetExtendedListViewStyle(listViewHandle, LVS_EX_TRACKSELECT);
If you don't want to choose hover but only want to handle hover, you can refer to:How can I detect if the mouse is over an item/subitem in a List View control?
Edit:
According to : TrackMouseEvent tracks mouse events in your window, but only if the events belong to your window
So you need to subclass your ListView and handle its window procedure:
WNDPROC oldListViewProc; //A global variable
oldListViewProc = (WNDPROC)SetWindowLongPtr(listViewHandle, GWL_WNDPROC, (LONG_PTR)ListViewProc);
......
LRESULT CALLBACK ListViewProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_MOUSEHOVER:
{
OutputDebugStringA("HOVER\n");
return 0;
}
case WM_MOUSEMOVE:
if (!mouseTracking)
{
// start tracking if we aren't already
TRACKMOUSEEVENT tme;
tme.cbSize = sizeof(TRACKMOUSEEVENT);
tme.dwFlags = TME_HOVER | TME_LEAVE;
tme.hwndTrack = hwnd; //This is the handle to the ListView window
tme.dwHoverTime = HOVER_DEFAULT;
mouseTracking = TrackMouseEvent(&tme);
}
break;
case WM_MOUSELEAVE:
mouseTracking = FALSE;
break;
}
return CallWindowProc(oldListViewProc, hwnd, msg, wParam, lParam);
}

Win 32 GUI c++ .bmp The image is not showing

I was actually following a tutorial. I really want to get an answer because I will need to add icons to the window down the line. Getting images to show in the window would be the first step.
Sorry for some reason the update I added did not go through before. My solution is geared towards Unicode.
The corrected updated file is below :
#include <windows.h>
#include <commctrl.h>
using namespace std;
LPCWSTR szClassName = L"myWindowClass";
HWND hLogo;
HBITMAP hLogoImage;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void loadPictures();
void parentControls(HWND);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int icmdshow)
{
HWND hWnd;
WNDCLASSW wc = { 0 };
wc.style = 0;
wc.lpszMenuName = NULL;
wc.lpszClassName = szClassName;
wc.lpfnWndProc = WndProc;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.hInstance = hInstance;
wc.hIcon = LoadIconW(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
wc.cbWndExtra = 0;
wc.cbClsExtra = 0;
if (!RegisterClassW(&wc))
{
const wchar_t Error01[] = L"Register Issue To Check On : "; /// Notice this
const wchar_t Error01_Caption[] = L"Error 01";
MessageBoxW(NULL, Error01, Error01_Caption, MB_OK | MB_ICONERROR);
return 0;
}
LPCWSTR parentWinTitle = L"My Window";
hWnd = CreateWindowW(szClassName, parentWinTitle, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 250, 200, NULL, NULL, NULL, NULL);
if (hWnd == NULL)
{
const wchar_t Error02[] = L"Window Creation Issue To Check On : ";
const wchar_t Error02_Caption[] = L"Window Creation Issue To Check On : ";
MessageBoxW(NULL, Error02, Error02_Caption, MB_OK | MB_ICONERROR);
}
ShowWindow(hWnd, icmdshow);
UpdateWindow(hWnd);
MSG msg = { 0 };
while (GetMessageW(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return 0;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
loadPictures(); /// Must be called first, Calling the Images function in Create
parentControls(hWnd);
break;
/* case WM_COMMAND:
switch (wParam)
{
}
break;
*/
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProcW(hWnd, message, wParam, lParam);
}
return 0;
}
void parentControls(HWND hWnd)
{
hLogo = CreateWindowW(WC_STATICW, NULL, WS_VISIBLE | WS_CHILD | SS_BITMAP, 70, 25, 100, 100, hWnd, NULL, NULL, NULL);
SendMessageW(hLogo, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hLogoImage);
}
void loadPictures()
{ /// bmp image save in file with main.cpp
LPCWSTR myBmp = L"bitmap1.bmp";
hLogoImage = (HBITMAP)LoadImageW(NULL, myBmp, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
}
case WM_COMMAND:
switch(wp)
{
}
break;
parentControls(hWnd); <--- never gets here
loadPictures(); /// Calling the Images function in Create
break;
parentControls and loadPictures are never reached in this switch statement.
loadPictures should be called first.
Remove the two lines, put them in WM_CREATE as follows:
case WM_CREATE:
loadPictures(); /// Calling the Images function in Create
parentControls(hWnd);
break;
Someone told me the answer should be here instead of updated above. I am sure I will be made aware that it is wrong if I add it here. I figure that is why the updates didn't take when I tried them before in the original post above. Either way the update/Answer is below.
#include <windows.h>
#include <commctrl.h>
using namespace std;
LPCWSTR szClassName = L"myWindowClass";
HWND hLogo;
HBITMAP hLogoImage;
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void loadPictures();
void parentControls(HWND);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int icmdshow)
{
HWND hWnd;
WNDCLASSW wc = { 0 };
wc.style = 0;
wc.lpszMenuName = NULL;
wc.lpszClassName = szClassName;
wc.lpfnWndProc = WndProc;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.hInstance = hInstance;
wc.hIcon = LoadIconW(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
wc.cbWndExtra = 0;
wc.cbClsExtra = 0;
if (!RegisterClassW(&wc))
{
const wchar_t Error01[] = L"Register Issue To Check On : "; /// Notice this
const wchar_t Error01_Caption[] = L"Error 01";
MessageBoxW(NULL, Error01, Error01_Caption, MB_OK | MB_ICONERROR);
return 0;
}
LPCWSTR parentWinTitle = L"My Window";
hWnd = CreateWindowW(szClassName, parentWinTitle, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 100, 100, 250, 200, NULL, NULL, NULL, NULL);
if (hWnd == NULL)
{
const wchar_t Error02[] = L"Window Creation Issue To Check On : ";
const wchar_t Error02_Caption[] = L"Window Creation Issue To Check On : ";
MessageBoxW(0, Error02, Error02_Caption, MB_OK | MB_ICONERROR);
}
ShowWindow(hWnd, icmdshow);
UpdateWindow(hWnd);
MSG msg = { 0 };
while (GetMessageW(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return 0;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
loadPictures(); /// Must be called first, Calling the Images function in Create
parentControls(hWnd);
break;
/* case WM_COMMAND:
switch (wParam)
{
}
break;
*/
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProcW(hWnd, message, wParam, lParam);
}
return 0;
}
void parentControls(HWND hWnd)
{
hLogo = CreateWindowW(WC_STATICW, NULL, WS_VISIBLE | WS_CHILD | SS_BITMAP, 70, 25, 100, 100, hWnd, NULL, NULL, NULL);
SendMessageW(hLogo, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hLogoImage);
}
void loadPictures()
{ /// bmp image save in file with main.cpp
LPCWSTR myBmp = L"bitmap1.bmp";
hLogoImage = (HBITMAP)LoadImageW(NULL, myBmp, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
}

ReOpen window from main window.

I have the main window open. It was created for me using visual studio. What I am attempting to do is have a main screen with 9 to 12 buttons. These buttons will then open up other windows. I am attempting with one button currently the "InventoryBtn". The inventory window open up and I am able to close it. The second time I try to open the window I get an error. It seems the window is already registered and cant be recreated. What am I doing incorrectly? I stepped thru it and aw that "Destroy:" is being called. The second time I try to show the inventory window the handle is uninitialized.
#include "stdafx.h"
#include "VehManager.h"
#include "M_Inventory.h"
#define MAX_LOADSTRING 100
#define InvWindowBtn 101
#define InvBtn 103
using namespace boost::gregorian;
HINSTANCE hInst;
WCHAR szTitle[MAX_LOADSTRING];
WCHAR szWindowClass[MAX_LOADSTRING];
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK InvWindowProcess(HWND, UINT, WPARAM, LPARAM);
HWND handleforInvWin;
WNDCLASSEX wxInv;
void CreateInventoryWindow();
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_VEHMANAGER, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE (IDC_VEHMANAGER));
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
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_VEHMANAGER));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_VEHMANAGER);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance;
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
MessageBoxA(NULL, "Main window creation failed.", "904.VehicleManager", MB_OK | MB_ICONINFORMATION);
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HFONT hfDefault;
switch (message)
{
case WM_CREATE:
{
HWND hInvBtn = CreateWindowEx(NULL, L"Button", L"INVENTORY", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
50, 220, 100, 24, hWnd, (HMENU)InvBtn, GetModuleHandle(NULL), NULL);
if (hInvBtn == NULL)
MessageBoxA(hWnd, "Could not create inventory button", "904.VehcleManager", NULL);
hfDefault = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
SendMessage(hInvBtn, WM_SETFONT, (WPARAM)hfDefault, MAKELPARAM(FALSE, 0));
}
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
switch (wmId)
{
case InvBtn:
{
CreateInventoryWindow();
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_RBUTTONDOWN:
MessageBox(NULL, L"Right button mouse clicks not allowed.", L"904.VehicleManager", NULL);
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
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;
}
void CreateInventoryWindow()
{
ZeroMemory(&wxInv, sizeof(WNDCLASSEX));
wxInv.cbClsExtra = NULL;
wxInv.cbSize = sizeof(WNDCLASSEX);
wxInv.cbWndExtra = NULL;
wxInv.hbrBackground = (HBRUSH)COLOR_WINDOW;
wxInv.hCursor = LoadCursor(NULL, IDC_ARROW);
wxInv.hIcon = NULL;
wxInv.hIconSm = NULL;
wxInv.hInstance = hInst;
wxInv.lpfnWndProc = (WNDPROC)InvWindowProcess;
wxInv.lpszClassName = L"Inventory";
wxInv.lpszMenuName = NULL;
wxInv.style = CS_HREDRAW | CS_VREDRAW;
if (!RegisterClassEx(&wxInv))
{
int nResult = GetLastError();
MessageBox(NULL, L"Inventory window class registration failed.", L"904.VehicleManager", MB_ICONEXCLAMATION);
return;
}
handleforInvWin = CreateWindowEx(NULL, wxInv.lpszClassName, L"Open Window 2", WS_OVERLAPPEDWINDOW,
200, 170, 640, 480, NULL, NULL, hInst, NULL);
if (!handleforInvWin)
{
MessageBox(NULL, L"Error with the inventory window handle.", L"904.VehManager", MB_ICONEXCLAMATION);
return;
}
ShowWindow(handleforInvWin, SW_SHOWNOACTIVATE);
UpdateWindow(handleforInvWin);
}
LRESULT CALLBACK InvWindowProcess(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HFONT hfDefault;
switch (message)
{
case WM_CREATE:
{
HWND hInvBtn = CreateWindowEx(NULL, L"Button", L"Close", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
50, 220, 100, 24, hwnd, (HMENU)InvBtn, GetModuleHandle(NULL), NULL);
if (hInvBtn == NULL)
MessageBoxA(hwnd, "Could not create inventory button", "904.VehcleManager", NULL);
hfDefault = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
SendMessage(hInvBtn, WM_SETFONT, (WPARAM)hfDefault, MAKELPARAM(FALSE, 0));
break;
}
case WM_DESTROY:
{
break;
}
case WM_COMMAND:
case InvBtn:
{
DestroyWindow(hwnd);
break;
}
break;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}

Win32 C++: Creation and Calling method from separate C++ file

I'm new to win32 c++ programming and I need help figuring out how to include methods in other files in my Win32 c++ application. I want to write methods in other files and include them in my code. I want to have a separate file, openFile, containing a method that is called from OpenWordGUI will pass back the file path. Is this possible?
Currently my code looks like the following:
// OpenWordDocGUI.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "OpenWordDocGUI.h"
#define MAX_LOADSTRING 100
//Defines for buttons
#define TSP_BUTTON 1
#define PCM_BUTTON 2
#define GO_BUTTON 3
//Defines Text boxes
#define TSP_BOX 101
#define PCM_BOX 102
//For text box
HWND TSPBox;
HWND PCMBox;
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
//Globals for
TCHAR szFilters[] = _T("Input files (*.*)\0*.*\0\0");
TCHAR szFilePathName[_MAX_PATH] = _T("");
//Store file paths in separate variables
TCHAR TSPFilePath[_MAX_PATH] = _T("");
TCHAR PCMFilePath[_MAX_PATH] = _T("");
int textBoxStat = 0;
TCHAR szInputBoxPathName[_MAX_PATH];
// 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_OPENWORDDOCGUI, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_OPENWORDDOCGUI));
// 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_OPENWORDDOCGUI));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_OPENWORDDOCGUI);
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;
}
//
// 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)
{
//Default
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
// Fill the OPENFILENAME structure for use in
// TSP/PCM buttons
OPENFILENAME ofn = {0};
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = hWnd;
ofn.lpstrFilter = szFilters;
ofn.lpstrFile = szFilePathName; // This will hold the file name
ofn.lpstrDefExt = _T("dat");
ofn.nMaxFile = _MAX_PATH;
ofn.lpstrTitle = _T("Open File");
ofn.Flags = OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
//////
switch (message)
{
case WM_CREATE:
//TSP MOA Button Creation
//Will bring up open file dialog when clicked
CreateWindow(TEXT("button"), TEXT("TSP MOA"),
WS_VISIBLE | WS_CHILD,
10, 10, 80, 25,
hWnd, (HMENU) TSP_BUTTON, NULL, NULL
);
//Window to show Selected TSP MOA
TSPBox = CreateWindow(TEXT("edit"), TEXT(""),
WS_BORDER | WS_CHILD | WS_VISIBLE,
100, 10, 400, 25,
hWnd, (HMENU) TSP_BOX,
NULL, NULL);
//PCM File Button Creation
//Will bring up open file dialog when clicked
CreateWindow(TEXT("button"), TEXT("PCM File"),
WS_VISIBLE | WS_CHILD,
10, 50, 80, 25,
hWnd, (HMENU) PCM_BUTTON, NULL, NULL
);
//Text box for PCM file creation
PCMBox = CreateWindow(TEXT("edit"), TEXT(""),
WS_BORDER | WS_CHILD | WS_VISIBLE,
100, 50, 400, 25,
hWnd, (HMENU) PCM_BOX,
NULL, NULL);
//Execute compare button
CreateWindow(TEXT("button"), TEXT("Compare"),
WS_VISIBLE | WS_CHILD,
10, 90, 80, 25,
hWnd, (HMENU) GO_BUTTON, NULL, NULL
);
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
case TSP_BUTTON:
//TSP Button clicked
//Open file dialog to select TSP MOA - done
//
TSPFilePath = openFile(TSP);
break;
case PCM_BUTTON:
//PCM Button clicked
//Open file dialog to select PCM file
PCMFilePath = openFile(PCM);
break;
case GO_BUTTON:
//Execute the following
//Read TSP MOA
//TSP MOA to Excel
//PCM to Excel
//compare TSP Excel to PCM
//Do data check
//Get data from TSP Text box
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;
}
Openfile would look something like:
#include <Commdlg.h>
#include <windows.h>
TCHAR* openFile(systemSel)
{
if (systemSel == "TSP")
{
//Set filter for openfile to word docs
} else {
//set filter for openfile to excel files
}
OPENFILENAME ofn ;
TCHAR szFile[MAX_PATH] ;
// open a file name
ZeroMemory( &ofn , sizeof( ofn));
ofn.lStructSize = sizeof ( ofn );
ofn.hwndOwner = NULL ;
ofn.lpstrFile = szFile ;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof( szFile );
ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex =1;
ofn.lpstrFileTitle = NULL ;
ofn.nMaxFileTitle = 0 ;
ofn.lpstrInitialDir=NULL ;
ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST ;
GetOpenFileName( &ofn )
return szFile
}
You need to have a header file which declares function openFile. Including this header in OpenWordDocGUI.cpp does the job.
There are a lot of tutorials on the internet showing how to write own header files to access functions within another .cpp file.
For example try this one: http://www.learncpp.com/cpp-tutorial/19-header-files

system-wide hook not run outside main program

I writing Hook Mouse system-wide (when mouse over any components in screen, Handle, classname, wndproc of it will display in my program).
But system-wide hook in my program not run when move mouse outside main program
I create DLL file successfully, but dont understand why it ONLY run as local hook (it run good in local my program - SCREEN AREA of my program).
This is source of hookDLL.cpp (DLL file):
#include "stdafx.h"
#include "Win32_Iczelion_HookDLL.h"
#define WM_MOUSEHOOK WM_USER+10
HINSTANCE hInstance;
HHOOK hHook;
HWND hWnd;
EXPORT HHOOK CALLBACK InstallHook(HWND);
EXPORT void CALLBACK UninstallHook(void);
EXPORT LRESULT CALLBACK MouseProc(int, WPARAM, LPARAM);
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
hInstance = hModule;
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
EXPORT HHOOK CALLBACK InstallHook(HWND hwnd)
{
hWnd = hwnd;
hHook = SetWindowsHookEx (WH_MOUSE, (HOOKPROC)MouseProc, hInstance, NULL);
return hHook;
}
EXPORT void CALLBACK UninstallHook()
{
UnhookWindowsHookEx(hHook);
}
EXPORT void test()
{
MessageBox(NULL, L"yeah", L"yeah", MB_OK);
}
EXPORT LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
CallNextHookEx(hHook, nCode, wParam, lParam);
POINT pt = {0};
GetCursorPos(&pt);
HANDLE handle = WindowFromPoint(pt);
PostMessage(hWnd, WM_MOUSEHOOK, (WPARAM)handle, 0);
return 0;
}
And this is source of hook.cpp (main program):
#include "stdafx.h"
#include "Win32_Iczelion_Hook.h"
#include "Win32_Iczelion_HookDLL.h"
#define WM_MOUSEHOOK WM_USER+10
#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
HWND hWndEHandle;
HWND hWndEClassName;
HWND hWndEWndProc;
HWND hWndBHook;
HWND hWndBExit;
HHOOK hHook;
BOOL HookFlag = FALSE;
// 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(_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_WIN32_ICZELION_HOOK, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32_ICZELION_HOOK));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
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_WIN32_ICZELION_HOOK));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WIN32_ICZELION_HOOK);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
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, 600, 300, NULL, NULL, hInstance, NULL);
hWndEHandle = CreateWindowEx(NULL, L"Edit", NULL,
WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOHSCROLL,
100,35,345,25,hWnd,(HMENU)IDC_HANDLE,hInstance,NULL);
hWndEClassName = CreateWindowEx(NULL, L"Edit", NULL,
WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOHSCROLL,
100,65,200,25,hWnd,(HMENU)IDC_CLASSNAME,hInstance,NULL);
hWndEWndProc = CreateWindowEx(NULL, L"Edit", NULL,
WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOHSCROLL,
100,95,200,25,hWnd,(HMENU)IDC_WNDPROC,hInstance,NULL);
hWndBHook = CreateWindowEx(NULL, L"Button", L"Hook",
WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON,
305,65,140,25,hWnd,(HMENU)IDC_HOOK,hInstance,NULL);
hWndBExit = CreateWindowEx(NULL, L"Button", L"Exit",
WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON,
305,95,140,25,hWnd,(HMENU)IDC_EXIT,hInstance,NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
LPWSTR buffer = 0;
RECT rect;
switch (message)
{
case WM_CREATE:
GetWindowRect(hWnd, &rect);
SetWindowPos(hWnd, HWND_TOPMOST, rect.left, rect.top, rect.right, rect.bottom, SWP_SHOWWINDOW);
break;
case WM_CLOSE:
if (HookFlag==TRUE)
UninstallHook();
DestroyWindow(hWnd);
case WM_MOUSEHOOK:
{
wchar_t buffer[256];
wsprintfW(buffer, L"%p", wParam);
SetDlgItemText(hWnd, IDC_HANDLE, buffer);
GetClassName((HWND)wParam, buffer, 128);
SetDlgItemText(hWnd, IDC_CLASSNAME, buffer);
DWORD buffer2 = GetClassLong((HWND)wParam,GCL_WNDPROC);
wsprintfW(buffer, L"%p", buffer2);
SetDlgItemText(hWnd, IDC_WNDPROC, buffer);
break;
}
case WM_COMMAND:
{
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
if (wmEvent==BN_CLICKED)
{
if (wmId==IDC_HOOK)
{
if (HookFlag==FALSE)
{
if (InstallHook(hWnd))
{
HookFlag = TRUE;
SetDlgItemText(hWnd, IDC_HOOK, L"Un hook");
}
}
else
{
UninstallHook();
SetDlgItemText(hWnd,IDC_HOOK,L"Hook");
HookFlag = FALSE;
SetDlgItemText(hWnd,IDC_CLASSNAME,NULL);
SetDlgItemText(hWnd,IDC_HANDLE,NULL);
SetDlgItemText(hWnd,IDC_WNDPROC,NULL);
}
}
else if (wmId==IDC_EXIT)
{
SendMessage(hWnd,WM_CLOSE,0,0);
}
}
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:
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;
}
Anyone can help me.
Last EDIT : corrected code.
The DLL is loaded, by Windows, in other processes, if they have the same bitness as your main process (and if they get the mouse). Consequence: the global hWnd variable in your Dll is always NULL and PostMessage fails.
Advices:
1 Always check the API's return code. You should have noticed that PostMessage failed.
2 When you are about to PostMessage in your DLL, if you see a NULL hWnd, use FindWindow to get the HWND and store it in hWnd for next time.
New version of the MouseProc DLL CallBack:
EXPORT LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
if ( nCode >= 0 ) {
PMOUSEHOOKSTRUCT pmhs = reinterpret_cast<PMOUSEHOOKSTRUCT>( lParam );
if ( hWnd == NULL ) hWnd = FindWindow( L"WIN32_ICZELION_HOOK", NULL );
if ( hWnd ) PostMessage(hWnd, WM_MOUSEHOOK, (WPARAM)pmhs->hwnd, 0);
}
return CallNextHookEx(0, nCode, wParam, lParam);
}
EDIT: make sure you run your progam (EXE) from a folder where the DLL has been rebuild). Create an empty solution (SLN) and add the 2 projects in it (vcxproj). Delete all "old" EXE and DLL. Rebuild.
EDIT added ScreenShot:
The EXE showing the class name of the Explorer folder bar
When DLL is loaded from another program (when you mouse over outside main program), hWnd is NULL, so you have to use FindWindow to get hWnd value of main program before PostMessage.