I want my application to run some code when the screen gets locked (Win 7 and 10). My application may be in the background too when user locks screen.
Anyone point me in right direction?
Thank you,
relayman
Use WTSRegisterSessionNotification() to register an HWND to receive WTS_SESSION_(UN)LOCK notifications via the WM_WTSSESSION_CHANGE window message.
You can use FMX's FormToHWND() function to obtain your Form's HWND. However, FireMonkey controls, including Forms, do not have an overridable WndProc() method to process window messages, like VCL does, so you will have to use the Win32 API's SetWindowLongPtr() or SetWindowSubclass() function (see Subclassing Controls on MSDN) to receive the WM_WTSSESSION_CHANGE window message:
class TMyForm : public TForm
{
...
#ifdef _Windows
private:
bool MonitoringWTS;
static LRESULT CALLBACK SubclassWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData);
protected:
virtual void __fastcall CreateHandle();
#endif
...
};
#ifdef _Windows
#include <FMX.Platform.Win.hpp>
#include <commctrl.h>
#include <wtsapi32.h>
void __fastcall TMyForm::CreateHandle()
{
MonitoringWTS = false;
TForm::CreateHandle();
// depending on which version of C++Builder you are using...
HWND hWnd = FormToHWND(this);
//HWND hWnd = WindowHandleToPlatform(Handle)->Wnd;
//HWND hWnd = FmxHandleToHWND(Handle);
if (!SetWindowSubclass(hWnd, &SubclassWndProc, 1, reinterpret_cast<DWORD_PTR>(this)))
throw Exception(_D("Could not subclass window"));
MonitoringWTS = WTSRegisterSessionNotification(hWnd, NOTIFY_FOR_THIS_SESSION);
if (!MonitoringWTS)
RaiseLastOSError();
}
LRESULT CALLBACK TMyForm::SubclassWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
switch (uMsg)
{
case WM_NCDESTROY:
{
WTSUnRegisterSessionNotification(hWnd);
reinterpret_cast<TMyForm*>(dwRefData)->MonitoringWTS = false;
RemoveWindowSubclass(hWnd, &SubclassWndProc, uIdSubclass);
break;
}
case WM_WTSSESSION_CHANGE:
{
TMyForm *pThis = reinterpret_cast<TMyForm*>(dwRefData);
switch (wParam)
{
case WTS_SESSION_LOCK:
// do something ...
break;
case WTS_SESSION_UNLOCK:
// do something ...
break;
}
return 0;
}
}
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
#endif
Alternatively, you can use the RTL's AllocateHWnd() function to create a hidden HWND and provide it with a custom WndProc() method:
class TMyForm : public TForm
{
...
#ifdef _Windows
private:
HWND WndForWTS;
bool MonitoringWTS;
void __fastcall WndProcForWTS(TMessage &Message);
public:
__fastcall TMyForm(TComponent *Owner);
__fastcall ~TMyForm();
#endif
...
};
#ifdef _Windows
#include <wtsapi32.h>
__fastcall TMyForm::TMyForm(TComponent *Owner)
: TForm(Owner)
{
WndForWTS = AllocateHWnd(&WndProcForWTS);
MonitoringWTS = WTSRegisterSessionNotification(WndForWTS, NOTIFY_FOR_THIS_SESSION);
if (!MonitoringWTS)
{
int err = GetLastError();
DeallocateHWnd(WndForWTS);
RaiseLastOSError(err);
}
}
__fastcall ~TMyForm();
{
DeallocateHWnd(WndForWTS);
}
void __fastcall TMyForm::WndProcForWTS(TMessage &Message)
{
switch (Message.Msg)
{
case WM_NCDESTROY:
{
if (MonitoringWTS)
{
WTSUnRegisterSessionNotification(WndForWTS);
MonitoringWTS = false;
}
WndForWTS = NULL;
break;
}
case WM_WTSSESSION_CHANGE:
{
switch (Message.WParam)
{
case WTS_SESSION_LOCK:
// do something ...
break;
case WTS_SESSION_UNLOCK:
// do something ...
break;
}
return;
}
}
Message.Result = DefWindowProc(WndForWTS, Message.Msg, Message.WParam, Message.LParam);
}
#endif
Related
The main goal is to block maximalize web browser window using subclassing and dll.
I have 2 apps: injector and the dll.
In injector app I load that dll, find window by title, get functions from dll and execute that functions ( their names are hook and unhook ) from dll. So this is standard injector. Of course I check is something NULL and I don't get any errors.
In dll I have 5 functions:
dllMain (here I only set global hInstance variable, which is in shared memory ):
BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
{
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
{
if (hInstance == NULL)
{
hInstance = hinstDLL;
}
break;
}
...
}
return TRUE;
}
Hook ( HandleofTarget is the HWND, which I get from FindWindow ; I use this function in injector ):
extern "C" __declspec(dllexport) bool hook( HWND HandleofTarget)
{
hTarget=HandleofTarget;
hhook=SetWindowsHookEx(WH_CBT,cbtHookProc,hInstance, GetWindowThreadProcessId(hTarget,NULL));
if(hhook==NULL)
return 0;
else
return 1;
}
Unhook ( here I unhook hooks - I use this function in injector):
extern "C" __declspec(dllexport) void unhook(void)
{
if(hhook != NULL)
UnhookWindowsHookEx( hhook );
}
cbtHookProc ( hook callback, where I change window procedure ):
LRESULT CALLBACK cbtHookProc( int code, WPARAM wParam, LPARAM lParam )
{
if( code < 0 ) return CallNextHookEx( 0, code, wParam, lParam );
if (code == HCBT_ACTIVATE)
{
if((HWND)(wParam)==hTarget)
{
if(done == FALSE)
{
g_OldWndProc =(WNDPROC)(SetWindowLongPtr ( (HWND)(wParam), GWLP_WNDPROC,reinterpret_cast<LONG_PTR>( NewWndProc )));
done = TRUE;
}
}
}
return CallNextHookEx( 0, code, wParam, lParam );
}
NewWndProc ( new Window procedure, where I would like to block maximalize ):
LRESULT CALLBACK NewWndProc( HWND hwnd, UINT mesg, WPARAM wParam, LPARAM lParam )
{
switch( mesg )
{
case WM_SYSCOMMAND:
{
if(wParam == SC_MAXIMIZE)
{
return 1;
}
}
break;
}
return CallWindowProc( g_OldWndProc, hwnd, mesg, wParam, lParam );
}
When I test this dll with other apps - it works. When I use this dll with web browser like Internet Edge and Google Chrome - it doesn't works. That web browser, which I try injected works slower, but I can still maximalize that window. When I debuq dll, in web browser after SetWindowsHookEx I see that hook is not NULL, but my code doesn't go to cbtHookProc. What is going on with web browser?
UPDATE:
One more time - thank you Strive Sun - MSFT for helping me.
I change the lines in cbtHookProc, but it still doesn't work. My cbtHookProc is don't called by webBrowser - that is problem.
When I looked at your gif I see something what I don't have and I think that is the problem. My injector app looks like this:
hDll = LoadLibrary( L"dllka10" );
hHookedWindow=FindWindow(TEXT("Chrome_WidgetWin_1"),TEXT("Nowa karta - Google Chrome"));
if( hDll && hHookedWindow)
{
qDebug()<<"hDll and hHookedWindow are not NULL!";
funHook =( MYPROC2 ) GetProcAddress( hDll, (LPCSTR) "hook" );
funUnhook = ( MYPROC ) GetProcAddress( hDll, (LPCSTR) "unhook" );
if( funHook )
{
qDebug()<<funHook(hHookedWindow);
}
}
I don't use CreateThread(). Is it important here?
UPDATED 2
LRESULT CALLBACK cbtHookProc( int code, WPARAM wParam, LPARAM lParam )
{
if( code < 0 ) return CallNextHookEx( 0, code, wParam, lParam );
std::fstream file;
file.open("C:\\Users\\tom\\Desktop\\logs.txt",std::ios::out|std::ios::app);
file<<"In cbtHook function!"<<std::endl;
file.close();
if (code == HCBT_MINMAX)
{
if (LOWORD(lParam) == SW_SHOWMAXIMIZED)
{
return 1;
}
}
return CallNextHookEx( 0, code, wParam, lParam );
}
When I run chrome application - my logs.txt is empty. When I run other app - I have logs.
UPDATED 3
In my dll I have:
#ifdef __GNUC__
HWND hTarget __attribute__((section (".shared"), shared)) =NULL;
HWND hApp __attribute__((section (".shared"), shared)) = NULL;
bool done __attribute__((section (".shared"), shared)) =FALSE;
HINSTANCE hInstance __attribute__((section (".shared"), shared)) =NULL;
HHOOK hhook __attribute__((section (".shared"), shared)) = NULL;
WNDPROC g_OldWndProc __attribute__((section (".shared"), shared)) = NULL;
#endif
#ifdef _MSC_VER
#pragma data_seg(".shared")
HWND hTarget=NULL;
HWND hApp = NULL;
bool done=FALSE;
HINSTANCE hInstance=NULL;
HHOOK hhook = NULL;
WNDPROC g_OldWndProc = NULL;
#pragma data_seg()
#pragma comment(linker, "/section:.shared,RWS")
#endif
in my injector I don't have any pragma - I have only ( QT ):
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <iostream>
#include "string.h"
#include "windows.h"
I can't reproduce your problem, but you can try another easier method.
HCBT_MINMAX : Specifies, in the low-order word, a show-window value
(SW_) specifying the operation. For a list of show-window values, see
the ShowWindow. The high-order word is undefined.
if (code == HCBT_MINMAX)
{
if (LOWORD(lParam) == SW_SHOWMAXIMIZED)
{
return 1;
}
}
No need to use HCBT_ACTIVATE to obtain window handles and compare their handles.
Updated:
Code works fine.
My code sample:
DLL:
// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include "stdio.h"
#include <windows.h>
HHOOK hCBT = NULL;
HWND hTarget;
HMODULE thisModule;
LRESULT CALLBACK _cbtProc(int code, WPARAM wParam, LPARAM lParam)
{
if (code < 0) return CallNextHookEx(0, code, wParam, lParam);
if (code == HCBT_MINMAX)
{
if (LOWORD(lParam) == SW_SHOWMAXIMIZED)
{
return 1;
}
}
return CallNextHookEx(0, code, wParam, lParam);
}
#ifdef __cplusplus //If used by C++ code.
extern "C" { //we need to export the C interface
#endif
__declspec(dllexport) BOOL WINAPI InstallHooks(HWND HandleofTarget)
{
hTarget = HandleofTarget;
DWORD tid = GetWindowThreadProcessId(hTarget, NULL);
hCBT = SetWindowsHookEx(WH_CBT, _cbtProc, thisModule, tid);
return (hCBT) ? TRUE : FALSE;
}
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus //If used by C++ code.
extern "C" { //we need to export the C interface
#endif
__declspec(dllexport) void WINAPI RemoveHooks()
{
UnhookWindowsHookEx(hCBT);
MessageBox(NULL, L"unhook", L" ", MB_OK);
hCBT = NULL;
}
#ifdef __cplusplus
}
#endif
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
thisModule = hModule;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
main.cpp
#include <Windows.h>
#include <stdio.h>
#include <psapi.h>
#include <shlwapi.h>
#include <tchar.h>
#pragma comment(lib,"Kernel32.lib")
#pragma comment(lib,"shlwapi.lib")
#pragma comment(linker, "/SECTION:.shared,RWS")
using namespace std;
HINSTANCE hinstDLL;
typedef void (*RemoveHooks)();
DWORD __stdcall CreateThreadFunc(LPVOID)
{
while (1)
{
if (GetAsyncKeyState(0x50) & 0x0001)
{
RemoveHooks removeHooks = (RemoveHooks)GetProcAddress(hinstDLL, "RemoveHooks");
removeHooks();
}
}
return 0;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == WM_DESTROY) {
PostQuitMessage(0);
}
return DefWindowProc(hwnd, message, wParam, lParam);
};
int main()
{
HWND hwnd = FindWindow(L"Chrome_WidgetWin_1", L"Google Translate - Google Chrome");
CreateThread(NULL, 0, CreateThreadFunc, 0, 0, 0);
hinstDLL = LoadLibrary(TEXT("D:\\Start from 11.2\\WM_CBT_DLL\\x64\\Debug\\WM_CBT_DLL.dll"));
BOOL(*InstallHooks)(HWND);
InstallHooks = (BOOL(*)(HWND)) GetProcAddress(hinstDLL, "InstallHooks");
BOOL l = InstallHooks(hwnd);
int err = GetLastError();
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
I have a global WH_CBT 32bit hook that I am using to determine when a window is about to be activated using HCBT_ACTIVATE.
How can I determine when the window is about to be deactivated?
There is the CBTACTIVATESTRUCT which has hWndActive, but that is sometimes 0x0and it wont work when switching to a 64bit window.
There is no HCBT_DEACTIVATE.
As#Remy Lebeau mentioned, you can use WM_ACTIVATE message. This message is sent both when the window is activated or deactivated.
Set a WH_CALLWNDPROC hook to capture the deactivated message, it will get the messages before the system sends them to the destination window procedure.
For more detail:
Use a function in a DLL for a non-local hook:
#include <Windows.h>
#include <stdio.h>
LRESULT CALLBACK wndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevinstance, PSTR szCmdLine, int iCmdShow) {
HWND hwnd;
//...
DWORD threadID = GetWindowThreadProcessId(hwnd, NULL);
HINSTANCE hinstDLL = LoadLibrary(TEXT("..\\Debug\\ProcHookDLL.dll"));
void (*AttachHookProc)(DWORD);
AttachHookProc = (void (*)(DWORD)) GetProcAddress(hinstDLL, "AttachHook");
AttachHookProc(threadID);
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){
//...
};
Here is the code for the DLL:
#include <Windows.h>
#include <stdio.h>
HMODULE thisModule;
HHOOK hook;
LRESULT CALLBACK LaunchListener(int nCode, WPARAM wParam, LPARAM lParam);
#ifdef __cplusplus // If used by C++ code,
extern "C" { // we need to export the C interface
#endif
__declspec(dllexport) void AttachHook(DWORD threadID) {
hook = SetWindowsHookEx(WH_CALLWNDPROC, LaunchListener, thisModule, threadID);
}
#ifdef __cplusplus
}
#endif
LRESULT CALLBACK LaunchListener(int nCode, WPARAM wParam, LPARAM lParam) {
// process event here
if (nCode >= 0) {
CWPSTRUCT* cwp = (CWPSTRUCT*)lParam;
if (cwp->message == WM_ACTIVATE) {
if (LOWORD(cwp->wParam) == WA_INACTIVE)
{
//the window being deactivated
}
else
{
//the window being activated
}
}
}
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
I took this example code from here that hooks a function to intercept keyboard events, and it works:
#include <Windows.h>
// variable to store the HANDLE to the hook. Don't declare it anywhere else then globally
// or you will get problems since every function uses this variable.
HHOOK _hook;
// This struct contains the data received by the hook callback. As you see in the callback function
// it contains the thing you will need: vkCode = virtual key code.
KBDLLHOOKSTRUCT kbdStruct;
// This is the callback function. Consider it the event that is raised when, in this case,
// a key is pressed.
LRESULT __stdcall HookCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode >= 0)
{
// the action is valid: HC_ACTION.
if (wParam == WM_KEYDOWN)
{
// lParam is the pointer to the struct containing the data needed, so cast and assign it to kdbStruct.
kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
// a key (non-system) is pressed.
if (kbdStruct.vkCode == VK_F1)
{
// F1 is pressed!
MessageBox(NULL, "F1 is pressed!", "key pressed", MB_ICONINFORMATION);
}
}
}
// call the next hook in the hook chain. This is nessecary or your hook chain will break and the hook stops
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
void SetHook()
{
// Set the hook and set it to use the callback function above
// WH_KEYBOARD_LL means it will set a low level keyboard hook. More information about it at MSDN.
// The last 2 parameters are NULL, 0 because the callback function is in the same thread and window as the
// function that sets and releases the hook. If you create a hack you will not need the callback function
// in another place then your own code file anyway. Read more about it at MSDN.
if (!(_hook = SetWindowsHookEx(WH_KEYBOARD_LL, HookCallback, NULL, 0)))
{
MessageBox(NULL, "Failed to install hook!", "Error", MB_ICONERROR);
}
}
void ReleaseHook()
{
UnhookWindowsHookEx(_hook);
}
void main()
{
// Set the hook
SetHook();
// Don't mind this, it is a meaningless loop to keep a console application running.
// I used this to test the keyboard hook functionality. If you want to test it, keep it in ;)
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
}
}
I am trying to make the similar code works for WH_GETMESSAGE to intercept WH_CREATE and WH_DESTROY messages, but it didn't work:
#include "stdafx.h"
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <psapi.h>
#include <iostream>
HHOOK _hook;
LRESULT CALLBACK GetMsgProc(_In_ int nCode, _In_ WPARAM wParam, _In_ LPARAM lParam)
{
std::cout << "Enter hook\n";
if (nCode >= 0)
{
// the action is valid: HC_ACTION.
std::cout << "HC_ACtION\n";
if (wParam != PM_REMOVE) return NULL;
MSG m = *((MSG*)lParam);
std::cout << "Message received\n";
TCHAR Buffer[MAX_PATH];
if (GetModuleFileNameEx(m.hwnd, 0, Buffer, MAX_PATH))
{
// At this point, buffer contains the full path to the executable
MessageBox(NULL, Buffer, L"key pressed", MB_ICONINFORMATION);
}
else
{
// You better call GetLastError() here
}
//CloseHandle(Hand);
}
// call the next hook in the hook chain. This is nessecary or your hook chain will break and the hook stops
return CallNextHookEx(_hook, nCode, wParam, lParam);
}
void SetHook()
{
if (!(_hook = SetWindowsHookEx(WH_GETMESSAGE, GetMsgProc, NULL, 0)))
{
MessageBox(NULL, L"Failed to install hook!", L"Error", MB_ICONERROR);
}
}
void ReleaseHook()
{
UnhookWindowsHookEx(_hook);
}
void main()
{
// Set the hook
SetHook();
// Don't mind this, it is a meaningless loop to keep a console application running.
// I used this to test the keyboard hook functionality. If you want to test it, keep it in ;)
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
}
}
MSDN specifies to use the function GetMsgProc with a predefined signature, but I don't see it does anything.
I am writing a global hook for WH_GETMESSAGE. But I am getting the error code 127 i.e.,ERROR_PROC_NOT_FOUND, when calling the GetProcAddress function from the dll. Its unable to find the GetMsgProc. Any idea why?
Also, I am new to this kind of programming, so apologies for any mistake that's not expected.
DLL File:
#include "windows.h"
#include <stdio.h>
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
return TRUE;
}
__declspec(dllexport) LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
MessageBox(NULL, TEXT("I am in"),TEXT("In a DLL"), MB_OK);
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
Program Loading the DLL file:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
typedef LRESULT(CALLBACK *LPGetMsgProc)(int nCode, WPARAM wParam, LPARAM lParam);
int main()
{
HMODULE hDll = LoadLibrary(_T("../../dllTouchInputHook/x64/Debug/dllTouchInputHook.dll"));
LPGetMsgProc proc = (LPGetMsgProc)GetProcAddress(hDll, "GetMsgProc");
if (proc == NULL) {
printf("The error code is %d", GetLastError());
}
HHOOK hMsgHook = SetWindowsHookEx(WH_GETMESSAGE, proc, hDll, 0);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hMsgHook);
return 0;
}
The function is not being found because it is not being exported as "GetMsgProc" like you are expecting. It is actually being exported more like "_GetMsgProc#12" (32bit) or "_GetMsgProc#20" (64bit) instead. If you want it exported as "GetMsgProc" then you need to use a .DEF file when compiling the DLL.
You shouldn't be implementing the hook in this manner to begin with. You should move the call to SetWindowsHookEx() inside the DLL itself, and then export a function to call it, eg:
#include "windows.h"
#include <stdio.h>
HINSTANCE hThisDLL;
HHOOK hMsgHook;
BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
hThisDLL = hinstDLL;
return TRUE;
}
LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
MessageBox(NULL, TEXT("I am in"), TEXT("In a DLL"), MB_OK);
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
__declspec(dllexport) BOOL WINAPI InstallHook()
{
if (!hMsgHook)
hMsgHook = SetWindowsHookEx(WH_GETMESSAGE, &GetMsgProc, hThisDll, 0);
return (hMsgHook != NULL);
}
__declspec(dllexport) VOID WINAPI UninstallHook()
{
if (hMsgHook)
{
UnhookWindowsHookEx(hMsgHook);
hMsgHook = NULL;
}
}
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
typedef BOOL (WINAPI *LPInstallHook)();
typedef VOID (WINAPI *LPUninstallHook)();
int main()
{
HMODULE hDll = LoadLibrary(_T("../../dllTouchInputHook/x64/Debug/dllTouchInputHook.dll"));
if (!hDll)
{
printf("The error code is %d", GetLastError());
return -1;
}
LPInstallHook installProc = (LPInstallHook) GetProcAddress(hDll, "InstallHook"); // or "_InstallHook"
LPUninstallHook uninstallProc = (installProc) ? (LPUninstallHook) GetProcAddress(hDll, "UninstallHook") : NULL; // or "_UninstallHook"
if (!(installProc && uninstallProc))
{
printf("The error code is %d", GetLastError());
FreeLibrary(hDll);
return -1;
}
if (!installProc())
{
printf("The error code is %d", GetLastError());
FreeLibrary(hDll);
return -1;
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
uninstallProc();
FreeLibrary(hDll);
return 0;
}
I have looked at the Microsoft documentation but it says that there should be no difference.
Note that this is a virtual ListView, so I supply the state icon index in the code implementing the LVN_GETDISPINFO message, if the LVIF_STATE flag is set in LV_ITEM::mask.
Does anyone know of any subtle differences which may cause this difference in behavior?
Not posting any sample code in your question does not exactly help...
This code works for me:
#include <Windows.h>
#include <commctrl.h>
#pragma comment(lib, "comctl32.lib")
typedef struct {
LPTSTR text;
UINT icon;
UINT stateicon;
} MYITEM;
HWND g_hLV=NULL;
MYITEM g_myitems[2]={{"item1",0,0},{"item2",2,2}};
LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp)
{
switch(msg)
{
case WM_NOTIFY:
if (lp)
{
NMLVDISPINFO*pLVDI=(NMLVDISPINFO*)lp;
NMLISTVIEW*&pLV=(NMLISTVIEW*&)pLVDI;
switch(pLVDI->hdr.code)
{
case LVN_GETDISPINFO:
if (LVIF_TEXT&pLVDI->item.mask) pLVDI->item.pszText=g_myitems[pLVDI->item.iItem].text;
if (LVIF_IMAGE&pLVDI->item.mask) pLVDI->item.iImage=g_myitems[pLVDI->item.iItem].icon;
if (LVIF_STATE&pLVDI->item.mask)
{
pLVDI->item.state=INDEXTOSTATEIMAGEMASK(1+g_myitems[pLVDI->item.iItem].stateicon);
pLVDI->item.stateMask=pLVDI->item.state;
}
return 0;
}
}
break;
case WM_CREATE:
{
g_hLV=CreateWindowEx(WS_EX_CLIENTEDGE,WC_LISTVIEW,0,WS_VISIBLE|WS_CHILD|LVS_OWNERDATA|LVS_REPORT|LVS_SHAREIMAGELISTS,0,0,0,0,hwnd,0,0,0);
LVCOLUMN lvc={LVCF_TEXT|LVCF_WIDTH};
lvc.pszText="dummy";
lvc.cx=99;
ListView_InsertColumn(g_hLV,0,&lvc);
SHFILEINFO sfi;
HIMAGELIST hil=(HIMAGELIST)SHGetFileInfo(".\\",FILE_ATTRIBUTE_DIRECTORY,&sfi,0,SHGFI_SMALLICON|SHGFI_SYSICONINDEX|SHGFI_USEFILEATTRIBUTES);
ListView_SetImageList(g_hLV,hil,LVSIL_SMALL);
ListView_SetImageList(g_hLV,hil,LVSIL_STATE);
g_myitems[1].stateicon=g_myitems[1].icon=sfi.iIcon;//assuming the imagelist has icons is wrong, so set at least one of them to a valid index
ListView_SetCallbackMask(g_hLV,LVIS_STATEIMAGEMASK);
ListView_SetItemCount(g_hLV,2);
}
return 0;
case WM_SIZE:
SetWindowPos(g_hLV,0,0,0,LOWORD(lp),HIWORD(lp),SWP_NOZORDER|SWP_NOACTIVATE);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwnd,msg,wp,lp);
}
int WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
InitCommonControls();
//This dialog subclassing is a ugly hack, but this is just sample code!
HWND hwnd=CreateWindowEx(0,WC_DIALOG,"LVTest",WS_OVERLAPPEDWINDOW,0,0,99,99,0,0,0,0);
SetWindowLongPtr(hwnd,GWLP_WNDPROC,(LONG_PTR)WndProc);
SendMessage(hwnd,WM_CREATE,0,0);
ShowWindow(hwnd,nShowCmd);
MSG msg;
while (GetMessage(&msg,0,0,0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}