Code:
#include <windows.h>
#include <objbase.h>
#include <commctrl.h>
#if defined(_MSC_VER)
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "ole32.lib")
#endif
#define MAIN_APP_WINDOW_CLASS TEXT("ScratchProgramWindowClass")
#define WC_IMAGEBOX WC_LISTVIEW
BOOL ImageBox_SetImage(HWND hwndImageBox, LPCTSTR szImagePath)
{
LVBKIMAGE lv = { 0 };
lv.ulFlags = LVBKIF_STYLE_NORMAL | LVBKIF_SOURCE_URL;
lv.pszImage = (LPTSTR) szImagePath; // full path required
return ListView_SetBkImage(hwndImageBox, &lv);
}
//+-----------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
switch(uMsg)
{
case WM_CREATE:
{
HWND hwndImage = CreateWindowEx(0, WC_IMAGEBOX, TEXT(""), WS_CHILD | WS_VISIBLE,
0, 0, 200, 200,
hwnd, NULL, (HMODULE) GetWindowLongPtr(hwnd, GWLP_HINSTANCE), NULL);
ImageBox_SetImage(hwndImage, TEXT("C:\\MyImage.jpg"));
return 0;
}
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
//+-----------------------------------------------------------------------------
BOOL SetupWindowClass( void )
{
WNDCLASSEX wc = { 0 };
INITCOMMONCONTROLSEX ice = { 0 };
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = GetModuleHandle(NULL);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIconSm = NULL;
wc.lpfnWndProc = WndProc;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hbrBackground = (HBRUSH) (COLOR_APPWORKSPACE + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = MAIN_APP_WINDOW_CLASS;
ice.dwSize = sizeof(ice);
ice.dwICC = ICC_LISTVIEW_CLASSES;
InitCommonControlsEx(&ice);
return (BOOL) RegisterClassEx(&wc);
}
//+-----------------------------------------------------------------------------
BOOL CALLBACK CreateAppWindow( int nCmdShow )
{
HWND hwnd;
hwnd = CreateWindowEx(0, MAIN_APP_WINDOW_CLASS, TEXT("Main Window"), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 500, 500,
NULL, NULL, GetModuleHandle(NULL), NULL);
if ( !hwnd )
return FALSE;
ShowWindow(hwnd, nCmdShow);
return TRUE;
}
//+-----------------------------------------------------------------------------
INT WINAPI WinMain( HINSTANCE hInstance, HINSTANCE reserved, LPSTR lpCommand, INT nCmdShow )
{
MSG msg;
BOOL bRet;
CoInitialize(NULL);
if( !SetupWindowClass() )
return -1;
if ( !CreateAppWindow( nCmdShow ) )
return -1;
while ( bRet = GetMessage(&msg, NULL, 0, 0) )
{
if (bRet != -1)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
CoUninitialize();
return (int) msg.wParam;
}
This method does not stretch the image so the image box should be the same size as the original image. Another solution is to