I want to implement a listbox and a slider in my window.
I use devcpp, not visual studio.
I have looked up for a way to do that and i have found nothing, except theoritical stuff like msdn.microsoft.com provides.
I want an example, the smallest kind of code to implement listbox and slider.
This is the closer and most helpfull link, but still, it uses visual studio.
Thanks.
I found what i was looking for, it seems that this is the only example code on the entire internet on making listboxes. In order to run it: download and open devc++ (which I use) or any other kind of compiler, open a new Windows application project (otherwise it won't work), erase any default code, paste this code and run it.
And this, is how you help others learn code.
http://www.dreamincode.net/forums/topic/291276-win32-listbox/
#include <Windows.h>
#define IDC_MAIN_BUTTON 101 // Button identifier
LRESULT CALLBACK WndProcedure(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
HWND hWndListL;
HWND hWndListR;
HWND hWndButton;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG Msg;
HWND hWnd;
//Settings All Window Class Variables
WNDCLASSEX WndClsEx;
WndClsEx.cbSize = sizeof(WNDCLASSEX);
WndClsEx.style = CS_HREDRAW | CS_VREDRAW;
WndClsEx.lpfnWndProc = WndProcedure;
WndClsEx.cbClsExtra = 0;
WndClsEx.cbWndExtra = 0;
WndClsEx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
WndClsEx.hInstance = hInstance;
WndClsEx.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
WndClsEx.hCursor = LoadCursor(NULL, IDC_ARROW);
WndClsEx.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
WndClsEx.lpszMenuName = NULL;
WndClsEx.lpszClassName = "My Window";
//Register Window Class
RegisterClassEx(&WndClsEx);
//Create Window
hWnd = CreateWindowEx(NULL, "My Window", "Windows Application", WS_OVERLAPPEDWINDOW, 200, 200, 640, 480, NULL, NULL, hInstance, NULL);
SendMessage(hWndListL, LB_ADDSTRING, NULL, (LPARAM)"one");
SendMessage(hWndListL, LB_ADDSTRING, NULL, (LPARAM)"two");
//Show Window
ShowWindow(hWnd, SW_SHOWNORMAL);
while(GetMessage(&Msg, NULL, 0, 0))
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return 0;
}
LRESULT CALLBACK WndProcedure(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
char buffer[50] = "";
switch(Msg)
{
case WM_CREATE:
//Create Listbox's
hWndListL = CreateWindowEx(NULL, "LISTBOX", NULL, WS_BORDER | WS_CHILD | WS_VISIBLE | ES_AUTOVSCROLL | LBS_NOTIFY, 50, 35, 200, 100, hWnd, NULL, GetModuleHandle(NULL), NULL);
hWndListR = CreateWindowEx(NULL, "LISTBOX", NULL, WS_BORDER | WS_CHILD | WS_VISIBLE | ES_AUTOVSCROLL | LBS_NOTIFY, 350, 35, 200, 100, hWnd, NULL, GetModuleHandle(NULL), NULL);
//Create Button
hWndButton = CreateWindowEx(NULL, "BUTTON", "OK", WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | WS_DISABLED, 50, 220, 100, 24, hWnd, (HMENU)IDC_MAIN_BUTTON, GetModuleHandle(NULL), NULL);
break;
case WM_COMMAND:
switch(HIWORD(wParam))
{
case LBN_SELCHANGE:
{
//EnableWindow( GetDlgItem( hWnd, (HMENU)IDC_BUTTON_MAIN ), TRUE );
EnableWindow(hWndButton, true);
break;
}
}
switch(LOWORD(wParam))
{
case IDC_MAIN_BUTTON:
{
//length = SendMessage(hWndListL, LB_GETTEXTLEN, NULL, NULL);
SendMessage(hWndListL, LB_GETTEXT, NULL, (LPARAM)buffer);
SendMessage(hWndListR, LB_ADDSTRING, NULL, (LPARAM)buffer);
SendMessage(hWndListL, LB_DELETESTRING, NULL, NULL);
EnableWindow(hWndButton, false);
break;
}
}
break;
case WM_DESTROY:
PostQuitMessage(WM_QUIT);
break;
}
return DefWindowProc(hWnd, Msg, wParam, lParam);
}
Here is example code of window with listbox:
#include <Windows.h>
/// unique class name
#define CLASS_NAME "MyWinapiClassNameWithUniqeSetOfCharactersThatAreNotMyPassword_50kz5S99g2Q88bTi3ne"
/// unique ID of our listbox command
#define IDC_LISTBOX_ID 123
static LRESULT WINAPI wndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ){
switch(msg){
case WM_CREATE:{
HWND listboxHwnd= CreateWindow( "LISTBOX", NULL, WS_CHILD | WS_VISIBLE | LBS_STANDARD | LBS_NOTIFY, 10, 10, 200, 100, hwnd, (HMENU)IDC_LISTBOX_ID, (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL);
SendMessage( listboxHwnd, LB_ADDSTRING, 0, (LPARAM)"List Item 0" );
SendMessage( listboxHwnd, LB_ADDSTRING, 0, (LPARAM)"List Item 1" );
SendMessage( listboxHwnd, LB_ADDSTRING, 0, (LPARAM)"List Item 2" );
SendMessage( listboxHwnd, LB_ADDSTRING, 0, (LPARAM)"List Item 3" );
SendMessage( listboxHwnd, LB_ADDSTRING, 0, (LPARAM)"List Item 4" );
SendMessage( listboxHwnd, LB_ADDSTRING, 0, (LPARAM)"List Item 5" );
SendMessage( listboxHwnd, LB_ADDSTRING, 0, (LPARAM)"List Item 6" );
SendMessage( listboxHwnd, LB_ADDSTRING, 0, (LPARAM)"List Item 7" );
SendMessage( listboxHwnd, LB_ADDSTRING, 0, (LPARAM)"List Item 8" );
SendMessage( listboxHwnd, LB_ADDSTRING, 0, (LPARAM)"List Item 9" );
}break;
case WM_COMMAND:{
switch( LOWORD(wParam) ){
case IDC_LISTBOX_ID:{
switch(HIWORD(wParam)){
case LBN_SELCHANGE:{ /// user have selected item in our listbox
int id= SendMessage( (HWND)lParam, LB_GETCARETINDEX, 0, 0 ); /// id of seleted item, starting from 0
char text[]= "Item 0 selected";
text[5] += id; /// thats one way of converting int to string :D
MessageBox( NULL, text, "Debug", MB_OK );
}break;
}
}break;
}
}break;
case WM_DESTROY:{
::PostQuitMessage(0);
}break;
}
return DefWindowProc( hwnd, msg, wParam, lParam);
}
int WINAPI WinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nShowCmd ){
WNDCLASSEX wc= {
sizeof(WNDCLASSEX),
CS_CLASSDC,
wndProc,
0,
0,
hInstance,
LoadIcon( NULL, IDI_APPLICATION ),
LoadCursor( NULL, IDC_ARROW ),
(HBRUSH)(COLOR_WINDOW+0),
NULL,
CLASS_NAME,
NULL
};
if( !RegisterClassEx(&wc) ){
MessageBox( NULL, "Fail to register window class.", "Error - Keyboardlord", MB_ICONERROR );
return -2;
}
HWND hwnd= CreateWindow( CLASS_NAME, "App Browser - Keyboardlord", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 250, 150, NULL, NULL, hInstance, NULL );
if( hwnd==NULL ){
MessageBox( NULL, "Fail to create window", "Error - Keyboardlord", MB_ICONERROR );
return -3;
}
ShowWindow( hwnd, nShowCmd );
MSG msg;
while( 0 < GetMessage( &msg, NULL, 0, 0) ){
TranslateMessage( &msg );
DispatchMessage( &msg );
}
::DestroyWindow( hwnd );
::UnregisterClass( CLASS_NAME, hInstance );
return 0;
}
Related
I'm trying to use my own custom images for creating a toolbar in a win32 winapi program. This is what I have ( in my WM_CREATE case ):
#define IDT_MAIN_TOOL 101
TBBUTTON tbb[ 1 ];
TBADDBITMAP tbab;
HWND hToolbar = CreateWindowEx( 0, TOOLBARCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | TBSTYLE_FLAT, 0, 0, 0, 0, hwnd, ( HMENU )IDT_MAIN_TOL, NULL, NULL );
SendMessage( hToolbar, TB_BUTTONSTRUCTSIZE, ( WPARAM )sizeof( TBBUTTON ), 0 );
tbab.hInst = HINST_COMMCTRL;
tbab.nID = IDB_HIST_LARGE_COLOR;
SendMessage( hToolbar, TB_ADDBITMAP, 0, ( LPARAM )&tbab );
ZeroMemory( tbb, sizeof( tbb ) );
tbb[ 0 ].iBitmap = HIST_BACK;
// I've also tried tbb[ 0 ].iBitmap = LoadIcon( NULL, "browse_back.ico" );
// However, iBitmap must be an integer and can't figure out how to use my 'browse_back.ico' image
tbb[ 0 ].fsState = TBSTATE_ENABLED;
SendMessage( hToolbar, TB_ADDBUTTONS, sizeof( tbb ) / sizeof( TBBUTTON ), ( LPARAM )&tbb );
I would like to use my own icon image: 'browse_back.ico' as the image for that toolbar button. How is this accomplished? Not sure if this is necessary but I'm using Microsoft Visual C++ 2010 Express.
Read the documentation:
iBitmap
Type: int
Zero-based index of the button image. Set this member to I_IMAGECALLBACK, and the toolbar will send the TBN_GETDISPINFO notification code to retrieve the image index when it is needed.
Version 5.81. Set this member to I_IMAGENONE to indicate that the button does not have an image. The button layout will not include any space for a bitmap, only text.
If the button is a separator, that is, if fsStyle is set to BTNS_SEP, iBitmap determines the width of the separator, in pixels. For information on selecting button images from image lists, see TB_SETIMAGELIST message.
So you need to create an image list using ImageList_Create(), add your ICO image to it using ImageList_Add() or ImageList_ReplaceIcon(), associate it with the toolbar using TB_SETIMAGELIST, and then you can set tbb[0].iBitmap to the ICO's index within the image list.
There are two ways that I know doing it. One is using TBADDBITMAP and the other one is using HIMAGELIST. In this example I use TBADDBITMAP but I personally prefer HIMAGELIST.
project.rc
#include "resource.h"
IDB_DOCUMENT BITMAP "document.bmp"
IDB_DRUGS BITMAP "drugs.bmp"
resource.h
#define IDTB_TOOLBAR 1000
#define IDB_DOCUMENT 1001
#define IDB_DRUGS 1002
#define ID_ADD_NEW 2000
tb.c
#include <windows.h>
#include <commctrl.h>
#include "resource.h"
const char ClassName[] = "ToolbarExample";
HWND hWndToolBar;
HINSTANCE g_hInstance;
LRESULT CALLBACK WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch (Msg)
{
case WM_CREATE:
{
TBADDBITMAP tbab1, tbab2;
TBBUTTON tbb[2];
hWndToolBar = CreateWindowEx(0, TOOLBARCLASSNAME, NULL, WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, hWnd,
(HMENU)IDTB_TOOLBAR, g_hInstance, NULL);
if (!hWndToolBar)
{
MessageBox(NULL, "ToolBar Failed.", "Error", MB_OK | MB_ICONERROR);
return 0;
}
SendMessage(hWndToolBar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
SendMessage(hWndToolBar, TB_SETBITMAPSIZE, (WPARAM)0, (LPARAM)MAKELONG(32, 32));
// Add Bitmaps
tbab1.hInst = g_hInstance;
tbab1.nID = IDB_DOCUMENT;
SendMessage(hWndToolBar, TB_ADDBITMAP, (WPARAM) 1, (LPARAM) &tbab1);
tbab2.hInst = g_hInstance;
tbab2.nID = IDB_DRUGS;
SendMessage(hWndToolBar, TB_ADDBITMAP, (WPARAM) 1, (LPARAM) &tbab2);
// Add Buttons
ZeroMemory(tbb, sizeof(tbb));
tbb[0].iBitmap = 0; // The index of the bitmap on toolbar bitmap collection
tbb[0].idCommand = ID_ADD_NEW;
tbb[0].fsState = TBSTATE_ENABLED;
tbb[0].fsStyle = TBSTYLE_BUTTON;
tbb[0].iString = SendMessage(hWndToolBar, TB_ADDSTRING, 0, (LPARAM)TEXT("Add New"));
tbb[1].iBitmap = 1;
tbb[1].idCommand = 0;
tbb[1].fsState = TBSTATE_ENABLED;
tbb[1].fsStyle = TBSTYLE_BUTTON;
tbb[1].iString = SendMessage(hWndToolBar, TB_ADDSTRING, 0, (LPARAM)TEXT("Drugs"));
SendMessage(hWndToolBar, TB_ADDBUTTONS, sizeof(tbb) / sizeof(TBBUTTON), (LPARAM)&tbb);
}
break;
case WM_COMMAND:
{
switch(LOWORD(wParam))
{
case ID_ADD_NEW:
{
MessageBox(NULL, "Toolbar Button One", "Success", MB_OK | MB_ICONINFORMATION);
}
break;
}
return 0;
}
break;
case WM_SIZE:
SendMessage(hWndToolBar, TB_AUTOSIZE, 0, 0);
break;
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return (DefWindowProc(hWnd, Msg, wParam, lParam));
}
return 0;
}
INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow)
{
InitCommonControls();
g_hInstance = hInstance;
WNDCLASS wc;
wc.style = 0;
wc.lpfnWndProc = (WNDPROC)WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = ClassName;
if (!RegisterClass(&wc))
{
MessageBox(NULL, "Failed To Register The Window Class.", "Error", MB_OK | MB_ICONERROR);
return 0;
}
HWND hWnd;
hWnd = CreateWindow(ClassName, "Toolbars", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
MessageBox(NULL, "Window Creation Failed.", "Error", MB_OK | MB_ICONERROR);
return 0;
}
ShowWindow(hWnd, SW_SHOW);
UpdateWindow(hWnd);
MSG Msg;
while (GetMessage(&Msg, NULL, 0, 0))
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return Msg.wParam;
}
I'm new to c / c++ programing language and am following an online tutorial about Win32. When I build and compile my project ( MS VS C++ 2010 Express ), i get this error: 'IDD_ABOUT' : undeclared identifier. I'm not sure how to fix this. :(
Main.cpp:
#include <Windows.h>
#define ID_FILE_EXIT 9001
#define ID_HELP_ABOUT 9002
const char g_szClassName[] = "myWindowClass";
BOOL CALLBACK AboutDlgProc( HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam )
{
switch( Message )
{
case WM_INITDIALOG:
return TRUE;
case WM_COMMAND:
switch( LOWORD( wParam ) )
{
case IDOK:
EndDialog( hwnd, IDOK );
break;
case IDCANCEL:
EndDialog( hwnd, IDCANCEL );
break;
}
break;
default:
return FALSE;
}
return TRUE;
}
LRESULT CALLBACK WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_CREATE:
{
HMENU hMenu, hSubMenu;
HICON hIcon, hIconSm;
hMenu = CreateMenu();
hSubMenu = CreatePopupMenu();
AppendMenu( hSubMenu, MF_STRING, ID_FILE_EXIT, "E&xit" );
AppendMenu( hMenu, MF_STRING | MF_POPUP, ( UINT )hSubMenu, "&File" );
hSubMenu = CreatePopupMenu();
AppendMenu( hSubMenu, MF_STRING, ID_HELP_ABOUT, "&About" );
AppendMenu( hMenu, MF_STRING | MF_POPUP, ( UINT )hSubMenu, "&Help" );
SetMenu( hwnd, hMenu );
hIcon = ( HICON )LoadImage( NULL, "menu_one.ico", IMAGE_ICON, 32, 32, LR_LOADFROMFILE );
if( hIcon )
SendMessage( hwnd, WM_SETICON, ICON_BIG, ( LPARAM )hIcon );
else
MessageBox( hwnd, "Could not load large icon!", "ERROR!", MB_OK | MB_ICONERROR );
hIconSm = ( HICON )LoadImage( NULL, "menu_one.ico", IMAGE_ICON, 16, 16, LR_LOADFROMFILE );
if( hIconSm )
SendMessage( hwnd, WM_SETICON, ICON_SMALL, ( LPARAM )hIconSm );
else
MessageBox( hwnd, "Could not load small icon!", "ERROR!", MB_OK | MB_ICONERROR );
}
break;
case WM_COMMAND:
switch( LOWORD( wParam ) )
{
case ID_FILE_EXIT:
PostMessage( hwnd, WM_CLOSE, 0, 0 );
break;
case ID_HELP_ABOUT:
{
int ret = DialogBox( GetModuleHandle( NULL ), MAKEINTRESOURCE( IDD_ABOUT ), hwnd, AboutDlgProc );
if( ret == IDOK )
MessageBox( hwnd, "Dialog exited with IDOK.", "Notice", MB_OK | MB_ICONINFORMATION );
else if( ret == IDCANCEL )
MessageBox( hwnd, "Dialog exited with IDCANCEL.", "Notice", MB_OK | MB_ICONINFORMATION );
else if( ret == -1 )
MessageBox( hwnd, "Dialog failed!", "Error", MB_OK | MB_ICONINFORMATION );
}
break;
}
break;
case WM_LBUTTONDOWN:
break;
case WM_CLOSE:
DestroyWindow( hwnd );
break;
case WM_DESTROY:
PostQuitMessage( 0 );
break;
default:
return DefWindowProc( hwnd, msg, wParam, lParam );
}
return 0;
}
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
WNDCLASSEX wc;
HWND hwnd;
MSG msg;
// Step 1: Registering the Window Class
wc.cbSize = sizeof( WNDCLASSEX );
wc.style = 1;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor( NULL, IDC_ARROW );
wc.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szClassName;
wc.hIconSm = NULL;
if( !RegisterClassEx( &wc ) )
{
MessageBox( NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK );
return 0;
}
hwnd = CreateWindowEx(
WS_EX_CLIENTEDGE,
g_szClassName,
"The title of my window",
WS_OVERLAPPEDWINDOW,
500, 200, 800, 600,
NULL, NULL, hInstance, NULL );
if( hwnd == NULL )
{
MessageBox( NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK );
return 0;
}
ShowWindow( hwnd, nCmdShow );
UpdateWindow( hwnd );
while( GetMessage( &msg, NULL, 0, 0 ) > 0 )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
return msg.wParam;
}
Resource.rc:
#include <Windows.h>
#ifndef IDC_STATIC
#define IDC_STATIC -1
#endif
IDD_ABOUT DIALOG DISCARDABLE 0, 0, 239, 66
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "My About Box"
FONT 8, "MS Sans Serif"
BEGIN
DEFPUSHBUTTON "&OK",IDOK,174,18,50,14
PUSHBUTTON "&Cancel",IDCANCEL,174,35,50,14
GROUPBOX "About this program...",IDC_STATIC,7,7,225,52
CTEXT "An example program showing how to use Dialog Boxes\r\n\r\nby theForger",IDC_STATIC,16,18,144,33
END
I have a feeling that Visual Studio Express doesn't include a proper resource editor that auto-generates resource includes, so I'm guessing you've created the .rc file manually. If so, you probably just need to define the symbol. Create an include file called resource.h and add this line to it:
#define IDD_ABOUT 100
Then include it at the top of your .cpp and .rc files:
#include <Windows.h>
#include "resource.h" // add this line
The windows headers define generic certain resource IDs (IDOK, IDCANCEL, IDC_STATIC, etc) but for anything else you'll need to add your own symbol. The values don't really matter - any number up to 65534 is ok as long as it doesn't clash with any other ID in use in the same "scope" (e.g. two controls in the one dialog should have different IDs, but you can re-use the same ID in another dialog).
My goal is to populate the client area of my window with a bunch of different child controls. Things like buttons check boxes and static text but I'm having a difficult time figuring out how to catch the button clicked message.
My Code:
#include <windows.h>
#include <CommCtrl.h>
#include "resource.h"
HMENU BUTTON1;
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, UINT wParam, LONG lParam) ;
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdParam, int nCmdShow)
{
static char szAppName[] = "Keyboarding" ;
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
HMENU hMenu;
hMenu = LoadMenu(hInstance, MAKEINTRESOURCE(IDR_MENU1));
if (!hPrevInstance)
{
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance ;
wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ;
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;
wndclass.hbrBackground = static_cast<HBRUSH>(GetStockObject (WHITE_BRUSH));
wndclass.lpszMenuName = NULL ;
wndclass.lpszClassName = szAppName ;
RegisterClass (&wndclass) ;
}
hwnd = CreateWindow (szAppName, // window class name
"Lab 6", // window caption
WS_OVERLAPPEDWINDOW, // window style
CW_USEDEFAULT, // initial x position
CW_USEDEFAULT, // initial y position
CW_USEDEFAULT,
CW_USEDEFAULT, // hmmmmm???
NULL, // parent window handle
hMenu, // window menu handle
hInstance, // program instance handle
NULL) ; // creation parameters
HWND button1 = CreateWindow( WC_BUTTON,
"Push Button",
WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
50,
50,
100,
24,
hwnd,
BUTTON1,
hInstance,
NULL);
HWND button2 = CreateWindow( WC_BUTTON,
"Auto Check Button?",
WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
50,
50,
100,
24,
hwnd,
NULL,
hInstance,
NULL);
HWND button3 = CreateWindow( WC_BUTTON,
"Push Button",
WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
50,
50,
100,
24,
hwnd,
NULL,
hInstance,
NULL);
HWND editControl = CreateWindow( WC_BUTTON,
"Push Button",
WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
50,
50,
100,
24,
hwnd,
NULL,
hInstance,
NULL);
HWND StaticControl = CreateWindow( WC_STATIC,
"Hello World",
WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
50,
100,
100,
24,
hwnd,
NULL,
hInstance,
NULL);
HWND ListBox = CreateWindow( WC_BUTTON,
"Push Button",
WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
50,
50,
100,
24,
hwnd,
NULL,
hInstance,
NULL);
ShowWindow (hwnd, nCmdShow) ;
UpdateWindow (hwnd) ;
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
return (int) msg.wParam ;
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, UINT wParam,
LONG lParam)
{
HDC hdc ;
PAINTSTRUCT ps ;
TEXTMETRIC tm;
RECT rClientRect;
RECT rWindowRect;
SIZE size;
int cButtons = 0;
switch (message)
{
case WM_COMMAND:
switch(LOWORD(wParam))
{
case BUTTON1:
break;
}
case WM_PAINT:
hdc = BeginPaint (hwnd, &ps) ;
EndPaint (hwnd, &ps) ;
return 0 ;
case WM_DESTROY:
PostQuitMessage (0) ;
return 0 ;
}
return DefWindowProc (hwnd, message, wParam, lParam) ;
}
I'm trying to catch my first button labaled button1 and has the "ID" BUTTON1. I have tried just catching them in my WM_COMMAND and it says my BUTTON1 is unidentified.
What you are looking for is:
case WM_COMMAND:
switch(LOWORD(wParam)) {
case BUTTON1: {
But before it will recognize BUTTON1 you will have to declare it in such a way that it can be recognized by the message handler: for example make it a global variable, instead of declaring it in the WinMain:
HMENU BUTTON1;
int WINAPI WinMaietcetc..
Let me know if this works !
OK, so i am writing this program in C++ that is supposed to append the clipboard text into the edit control inside the Auto-Clipboard tab. I have setup the program so that it supports unicode text.
The program appends the text correctly when i copy text outside the program. But if i copy text that is from the program, it shows me as if it is copying ansi characters that needs to be converted int unicode.
I am not sure if the problem is from the edit control or from the Clipboard. Is the edit control output not in unicode? Or is the clipboard copying as ansi and pasting as unicode?
Edit: So i find out that according to MSDN documentations, WM_COPY in edit controls are handled in CF_TEXT mode instead of CF_UNICODETEXT for the clipboard:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms649022(v=vs.85).aspx
And so, i added some subclassing starting with my AutoClipboardEdit control but for some reason i get currupted heap error on WM_DRAWCLIPBOARD messages. So i am stuck there:
Edit2: I got it working by not freeing the allocated memory of the text string used on the clipboard. In this case the name of the variable is hMem2. It seems that if i free hMem2, the program crashes with a "corrupted heap" error. My guess is that the OS itself manages and frees the memory. It does seem possible since the SetClipboardData argument for the data is a pointer. I also tried to test if memory actually leaked by sending a WM_COPY message into a infinite loop to see if the heap would increase forever; but far it didn't seem so.
So, i need someone to confirm to me that there is no memory leak or that the OS actually does manage and free the clipboard accordingly.
Here is the complete source code:
#define UNICODE
#define _UNICODE
#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")
#include <tchar.h>
#include <Windows.h>
#include <CommCtrl.h>
#include <sstream>
using namespace std;
TCHAR temp[1024];
enum TabIndexes
{
ID_ReadingPageTab,
ID_AutoClipboardTab
};
enum WindowControls
{
ID_SelectAll,
ID_TabControls,
ID_ReadingPageEdit,
ID_AutoClipboardEdit,
ID_AutoClipboardCheckbox,
ID_AutoReadCheckbox,
ID_AutoClearCheckbox,
ID_ReadPauseResumeButton,
ID_StopButton
};
//***************Global Variables***************
HWND MainWindowHandle;
HWND ClipboardViewer;
HWND TabControls;
HWND ReadingPageEdit;
HWND AutoClipboardEdit;
HWND AutoClipboardCheckbox;
HWND AutoReadCheckbox;
HWND AutoClearCheckbox;
HWND ReadPauseResumeButton;
HWND StopButton;
RECT WindowReactangle;
RECT EditControlsDimension;
HACCEL SelectAll;
int Textlength;
void ShowReport()
{
LPTSTR ErrorText = NULL;
FormatMessage
(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, //dwFlags
NULL, //lpSource
GetLastError(), //dwMessageId
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //dwLanguageId
(LPTSTR)&ErrorText, //lpBuffer
0, //nSize
NULL //*Arguments
);
MessageBox(NULL, ErrorText, TEXT("Last Error:"), MB_OK);
}
void OutputBox(LPTSTR OutputText)
{
MessageBox(NULL, OutputText, _T("WARNING!!!"), MB_OK);
}
WNDPROC OldProc;
LRESULT CALLBACK EditControl
(
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
WPARAM StartOfSelectection;
LPARAM EndOfSelection;
int SelectionSize;
int TextSize;
TCHAR* hMem1;
TCHAR* hMem2;
if (uMsg == WM_COPY)
{
OpenClipboard(NULL);
SendMessage(hwnd, EM_GETSEL, (WPARAM)&StartOfSelectection, (LPARAM)&EndOfSelection);
SelectionSize = EndOfSelection - StartOfSelectection + 1;
TextSize = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0);
TextSize -= (TextSize - EndOfSelection - 1);
hMem1 = new TCHAR[TextSize]();
ZeroMemory(hMem1, TextSize*sizeof(TCHAR));
SendMessage(hwnd, WM_GETTEXT, TextSize, (LONG)hMem1);
hMem2 = new TCHAR[SelectionSize]();
ZeroMemory(hMem2, SelectionSize*sizeof(TCHAR));
for(int Index=0; StartOfSelectection<EndOfSelection; ++StartOfSelectection)
hMem2[Index++] = hMem1[StartOfSelectection];
SetClipboardData(CF_UNICODETEXT, (HANDLE)hMem2);
CloseClipboard();
delete[] hMem1;
//delete[] hMem2;
}
return OldProc(hwnd, uMsg, wParam, lParam);
}
void CreateControls(HWND hWndParent)
{
GetClientRect(hWndParent, &WindowReactangle);
const INITCOMMONCONTROLSEX CommonControls = {sizeof(INITCOMMONCONTROLSEX), ICC_TAB_CLASSES};
InitCommonControlsEx(&CommonControls);
TabControls = CreateWindow
(
WC_TABCONTROL, //lpClassName
NULL, //lpWindowName
WS_VISIBLE | WS_CHILD, //dwStyle
WindowReactangle.left, //x
WindowReactangle.top, //y
WindowReactangle.right, //nWidth
WindowReactangle.bottom - 100, //nHeight
hWndParent, //hWndParent
(HMENU)ID_TabControls, //hMenu
NULL, //hInstance
NULL //lpParam
);
TCITEM TabItemStructure = {0};
TabItemStructure.mask = TCIF_TEXT;
TabItemStructure.pszText = _T("Reading Page");
SendMessage(TabControls, TCM_INSERTITEM, ID_ReadingPageTab, (LPARAM)&TabItemStructure);
TabItemStructure.pszText = _T("Auto-Clipboard");
SendMessage(TabControls, TCM_INSERTITEM, ID_AutoClipboardTab, (LPARAM)&TabItemStructure);
ACCEL AcceleratorStructure;
AcceleratorStructure.fVirt = FCONTROL | FVIRTKEY;
AcceleratorStructure.key = 0x41;
AcceleratorStructure.cmd = ID_SelectAll;
SelectAll = CreateAcceleratorTable(&AcceleratorStructure, 1);
ReadingPageEdit = CreateWindow
(
_T("EDIT"), //lpClassName
NULL, //lpWindowName
WS_VISIBLE | WS_CHILD | WS_VSCROLL | WS_BORDER | ES_MULTILINE, //dwStyle
5, //x
30, //y
WindowReactangle.right - 10, //nWidth
WindowReactangle.bottom - 135, //nHeight
TabControls, //hWndParent
(HMENU)ID_ReadingPageEdit, //hMenu
NULL, //hInstance
NULL //lpParam
);
AutoClipboardEdit = CreateWindow
(
_T("EDIT"), //lpClassName
NULL, //lpWindowName
WS_CHILD | WS_VSCROLL | WS_BORDER | ES_MULTILINE, //dwStyle
5, //x
30, //y
WindowReactangle.right - 10, //nWidth
WindowReactangle.bottom - 135, //nHeight
TabControls, //hWndParent
(HMENU)ID_AutoClipboardEdit, //hMenu
NULL, //hInstance
NULL //lpParam
);
AutoClipboardCheckbox = CreateWindow
(
_T("BUTTON"), //lpClassName
_T("Auto-Clipboard"), //lpWindowName
BS_AUTOCHECKBOX | WS_VISIBLE | WS_CHILD, //dwStyle
10, //x
WindowReactangle.bottom -100 +10, //y
150, //nWidth
25, //nHeight
hWndParent, //hWndParent
(HMENU)ID_AutoClipboardCheckbox, //hMenu
NULL, //hInstance
NULL //lpParam
);
SendMessage(AutoClipboardCheckbox, BM_CLICK, TRUE, 0);
OldProc = (WNDPROC)SetWindowLongPtr(AutoClipboardEdit, GWLP_WNDPROC, (LONG)EditControl);
AutoReadCheckbox = CreateWindow
(
_T("BUTTON"), //lpClassName
_T("Auto-Read"), //lpWindowName
BS_AUTOCHECKBOX | WS_VISIBLE | WS_CHILD, //dwStyle
10, //x
WindowReactangle.bottom -100 +35, //y
150, //nWidth
25, //nHeight
hWndParent, //hWndParent
(HMENU)ID_AutoReadCheckbox, //hMenu
NULL, //hInstance
NULL //lpParam
);
AutoClearCheckbox = CreateWindow
(
_T("BUTTON"), //lpClassName
_T("Auto-Clear"), //lpWindowName
BS_AUTOCHECKBOX | WS_VISIBLE | WS_CHILD, //dwStyle
10, //x
WindowReactangle.bottom -100 +60, //y
150, //nWidth
25, //nHeight
hWndParent, //hWndParent
(HMENU)ID_AutoReadCheckbox, //hMenu
NULL, //hInstance
NULL //lpParam
);
}
LRESULT WINAPI MainWindowProcedure
(
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
switch(uMsg)
{
//Clipboard Events
case WM_CHANGECBCHAIN:
if ((HWND)wParam == ClipboardViewer)
ClipboardViewer = (HWND)lParam;
return 0;
case WM_DRAWCLIPBOARD:
OpenClipboard(NULL);
SendMessage(AutoClipboardEdit, EM_SETSEL, (WPARAM)-1, (LPARAM)-1);
SendMessage(AutoClipboardEdit, EM_REPLACESEL, 0, (LPARAM)GetClipboardData(CF_UNICODETEXT)); //CF_TEXT //CF_UNICODETEXT
CloseClipboard();
break;
//Window Controls Events
case WM_COMMAND:
switch (LOWORD(wParam))
{
case ID_SelectAll:
if (HIWORD(wParam)==1)
SendMessage(GetFocus(), EM_SETSEL, (WPARAM)0, (LPARAM)-1);
break;
case ID_AutoClipboardCheckbox:
if (SendMessage(AutoClipboardCheckbox, BM_GETCHECK, 0, 0) == BST_CHECKED)
ClipboardViewer = SetClipboardViewer(hwnd);
else
ChangeClipboardChain(hwnd, ClipboardViewer);
break;
}
return 0;
//Tab Controls Events
case WM_NOTIFY:
if (SendMessage(TabControls, TCM_GETCURSEL, 0, 0))
{
ShowWindow(ReadingPageEdit, SW_HIDE);
ShowWindow(AutoClipboardEdit, SW_SHOW);
} else
{
ShowWindow(AutoClipboardEdit, SW_HIDE);
ShowWindow(ReadingPageEdit, SW_SHOW);
}
break;
//Main Window Events
case WM_SIZE:
{
int LOPARAM = lParam & 0xFFFF;
int HIPARAM = lParam >> 16;
SetWindowPos(TabControls, NULL, 0, 0, LOPARAM, HIPARAM-100, SWP_DRAWFRAME);
SetWindowPos(ReadingPageEdit, NULL, 5, 30, LOPARAM-10, HIPARAM-100-35, SWP_DRAWFRAME);
SetWindowPos(AutoClipboardEdit, NULL, 5, 30, LOPARAM-10, HIPARAM-100-35, SWP_DRAWFRAME);
SetWindowPos(AutoClipboardCheckbox, NULL, 10, HIPARAM-100+10, 150, 25, SWP_DRAWFRAME);
SetWindowPos(AutoReadCheckbox, NULL, 10, HIPARAM-100+35, 150, 25, SWP_DRAWFRAME);
SetWindowPos(AutoClearCheckbox, NULL, 10, HIPARAM-100+60, 150, 25, SWP_DRAWFRAME);
return 0;
}
case WM_CREATE:
CreateControls(hwnd);
return 0;
case WM_DESTROY:
DestroyAcceleratorTable(SelectAll);
ChangeClipboardChain(hwnd, ClipboardViewer);
PostQuitMessage(ERROR_SUCCESS);
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
void CreateMainWindow()
{
WNDCLASSEX WindowClassStructure;
WindowClassStructure.cbSize = sizeof(WNDCLASSEX);
WindowClassStructure.style = CS_HREDRAW | CS_VREDRAW;
WindowClassStructure.lpfnWndProc = MainWindowProcedure;
WindowClassStructure.cbClsExtra = 0;
WindowClassStructure.cbWndExtra = 0;
WindowClassStructure.hInstance = NULL;
WindowClassStructure.hIcon = LoadIcon(NULL, IDI_INFORMATION);
WindowClassStructure.hCursor = LoadCursor(NULL, IDC_ARROW);
WindowClassStructure.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
WindowClassStructure.lpszMenuName = NULL;
WindowClassStructure.lpszClassName = _T("MainClass");
WindowClassStructure.hIconSm = LoadIcon(NULL, IDI_INFORMATION);
RegisterClassEx(&WindowClassStructure);
MainWindowHandle = CreateWindow
(
_T("MainClass"), //lpClassName
_T("Clipboard Reader"), //lpWindowName
WS_VISIBLE | WS_OVERLAPPEDWINDOW, //dwStyle
CW_USEDEFAULT, //x
CW_USEDEFAULT, //y
640, //nWidth
480, // nHeight
NULL, //hWndParent
NULL, //hMenu
NULL, //hInstance
NULL //lpParam
);
}
int WINAPI _tWinMain
(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow
)
{
CreateMainWindow();
MSG MessageStructure = {0};
while(MessageStructure.message != WM_QUIT)
{
if (PeekMessage(&MessageStructure, NULL, 0, 0, PM_REMOVE))
{
if (!TranslateAccelerator(MainWindowHandle, SelectAll, &MessageStructure))
{
TranslateMessage(&MessageStructure);
DispatchMessage(&MessageStructure);
}
}
}
return MessageStructure.wParam;
}
How I can change the background image of a window at runtime in WIN32?
I have created the window using CreateWindow(). Then I have a LoadImage Button which opens a model dialog box (open file dialog)... Now I want to use the file name returned by this dialog box as the image of the window.
There is no native concept for the window background, you have to manually paint your image, usually in the WM_ERASEBKGND message. If you are using MFC you can check this article: http://www.codeproject.com/KB/graphics/picturewindow.aspx
A piece of sample code of what CoreyStup explains, in the window callback:
switch (message)
{
case WM_CREATE:
{
HBITMAP hImage = (HBITMAP)LoadImage(NULL, L"guibg.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
HWND hImageView = CreateWindowEx(NULL, L"STATIC", NULL, SS_BITMAP | WS_VISIBLE | WS_CHILD, 0, 00, 500, 600, hWnd, (HMENU)IMAGE_VIEW, GetModuleHandle(NULL), NULL);
SendMessage(hImageView, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hImage);
...
Credits also to fritzone who answered this on this similar thread: How to add picture box in win32 API using visual c++
NOTE: Use bitmaps generated by paint, otherwise LoadImage may return NULL without an error and the image will be invisible.
compile the code below.
write your file name in textbox and press change background.
i use mingw 4.7.
you can only use .bmp images, if you want to use other image you have to use GdiPluse.
#include <windows.h>
//variables
HWND hwnd01, label01;
HBITMAP hBitmap01 = NULL;
//functions
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow )
{
MSG msg ;
WNDCLASS wc = {0};
wc.lpszClassName = TEXT( "GUI01" );
wc.hInstance = hInstance ;
wc.hbrBackground = GetSysColorBrush(COLOR_3DFACE);
wc.lpfnWndProc = WndProc ;
wc.hCursor = LoadCursor(0, IDC_ARROW);
RegisterClass(&wc);
hwnd01 = CreateWindow( wc.lpszClassName, TEXT("GUI01 Headline"),
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
150, 150, 330, 150, 0, 0, hInstance, 0);
while( GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
LRESULT CALLBACK WndProc( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch(msg)
{
case WM_CREATE:
{
CreateWindow(TEXT("button"), TEXT("Change Background"),
WS_VISIBLE | WS_CHILD ,
20, 50, 140, 25,
hwnd, (HMENU) 1, NULL, NULL);
CreateWindow(TEXT("button"), TEXT("Quit"),
WS_VISIBLE | WS_CHILD ,
190, 50, 80, 25,
hwnd, (HMENU) 2, NULL, NULL);
label01 = CreateWindow(TEXT("Edit"), TEXT("Label"),
WS_VISIBLE | WS_CHILD,
20, 10, 280, 25,
hwnd, (HMENU) 3, NULL, NULL);
break;
}
case WM_COMMAND:
{
if (LOWORD(wParam) == 1) {
TCHAR* string01 = new TCHAR[300];
GetWindowText(label01, string01, 300);
hBitmap01 = (HBITMAP)LoadImage(NULL, string01, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
if (hBitmap01==NULL)
MessageBox(NULL, "Error Loading Image.", "ERROR", MB_ICONWARNING | MB_DEFBUTTON2);
else
InvalidateRect(hwnd01, NULL, TRUE);
}
if (LOWORD(wParam) == 2) {
PostQuitMessage(0);
}
break;
}
case WM_PAINT:
{
PAINTSTRUCT ps01;
HDC hdc01;
BITMAP bitmap01;
HDC hdcMem01;
HGDIOBJ oldBitmap01;
hdc01 = BeginPaint(hwnd01, &ps01);
hdcMem01 = CreateCompatibleDC(hdc01);
oldBitmap01 = SelectObject(hdcMem01, hBitmap01);
GetObject(hBitmap01, sizeof(bitmap01), &bitmap01);
BitBlt(hdc01, 0, 0, bitmap01.bmWidth, bitmap01.bmHeight, hdcMem01, 0, 0, SRCCOPY);
SelectObject(hdcMem01, oldBitmap01);
DeleteDC(hdcMem01);
EndPaint(hwnd01, &ps01);
break;
}
case WM_DESTROY:
{
PostQuitMessage(0);
break;
}
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
A static control can have a background image (although its limited to bitmaps). You can put a child static control inside of your window (sized edge to edge) and set it as the background.
If you want fancy image handling like transparency, you'll need to do that manually.