How to strech a bitmap using StretchBlt? - winapi

so I have written an application that loads bitmaps. But I would like to stretch the bitmap loaded in a way that all of them would have the same size. How can I go about implementing such a thing with StretchBlt? Here is my function that handles the bitmaps:
hBitmap = (HBITMAP)::LoadImageA(NULL, userSelectedFile, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
if (hBitmap == NULL)
{
::MessageBox(NULL, TEXT("LoadImage Failed"), TEXT("Error"), MB_OK);
return false;
}
HDC hLocalDC;
hLocalDC = ::CreateCompatibleDC(hWinDC);
if (hLocalDC == NULL)
{
::MessageBox(NULL, TEXT("CreateCompatibleDC Failed"), TEXT("Error"), MB_OK);
return false;
}
BITMAP qBitmap;
int iReturn = GetObject(reinterpret_cast<HGDIOBJ>(hBitmap), sizeof(BITMAP), reinterpret_cast<LPVOID>(&qBitmap));
if (!iReturn)
{
::MessageBox(NULL, TEXT("GetObject Failed"), TEXT("Error"), MB_OK);
return false;
}
HBITMAP hOldBmp = (HBITMAP)::SelectObject(hLocalDC, hBitmap);
if (hOldBmp == NULL)
{
::MessageBox(NULL, TEXT("SelectObject Failed"), TEXT("Error"), MB_OK);
return false;
}
BOOL qRetBlit = ::BitBlt(hWinDC, 0, 0, qBitmap.bmWidth, qBitmap.bmHeight, hLocalDC, 0, 0, SRCCOPY);
if (!qRetBlit)
{
::MessageBox(NULL, TEXT("Blit Failed"), TEXT("Error"), MB_OK);
return false;
}
::SelectObject(hLocalDC, hOldBmp);
::DeleteDC(hLocalDC);
::DeleteObject(hBitmap);
return true;
Would I have to replace StretchBlt with BitBlt?
UPDATE: I have managed to get StretchBlt to work but apparently all my images are overlapping each other. Here's the code so far:
hBitmap = (HBITMAP)::LoadImageA(NULL, myFile, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
// Verify that the image was loaded
if (hBitmap == NULL)
{
::MessageBox(NULL, TEXT("LoadImage Failed"), TEXT("Error"), MB_OK);
return false;
}
HDC hLocalDC;
hLocalDC = ::CreateCompatibleDC(hWinDC);
// Verify that the device context was created
if (hLocalDC == NULL)
{
::MessageBox(NULL, TEXT("CreateCompatibleDC Failed"), TEXT("Error"), MB_OK);
return false;
}
BITMAP qBitmap;
int iReturn = GetObject(reinterpret_cast<HGDIOBJ>(hBitmap), sizeof(BITMAP), reinterpret_cast<LPVOID>(&qBitmap));
if (!iReturn)
{
::MessageBox(NULL, TEXT("GetObject Failed"), TEXT("Error"), MB_OK);
return false;
}
HBITMAP hOldBmp = (HBITMAP)::SelectObject(hLocalDC, hBitmap);
if (hOldBmp == NULL)
{
::MessageBox(NULL, TEXT("SelectObject Failed"), TEXT("Error"), MB_OK);
return false;
}
/*BOOL qRetBlit = ::BitBlt(hWinDC, xPos, yPos, qBitmap.bmWidth, qBitmap.bmHeight, hLocalDC, 0, 0, SRCCOPY);
if (!qRetBlit)
{
::MessageBox(NULL, TEXT("Blit Failed"), TEXT("Error"), MB_OK);
return false;
}*/
sx = GetSystemMetrics(SM_CXSCREEN);
sy = GetSystemMetrics(SM_CXSCREEN);
BOOL qStretchBlit = StretchBlt(hWinDC, 0, 0, sx/2, sy/2, hLocalDC, 0, 0, sx, sy, SRCCOPY);
if (!qStretchBlit)
{
MessageBox(NULL, TEXT("StretchBlt Failed"), TEXT("Error"), MB_OK);
return false;
}
// Adjust positioning (not perfect)
if (iOldCounter > iCounter)
{
xPos += MOVE_X_POS;
if (xPos >= NEW_ROW_POS)
{
xPos = 0;
yPos += MOVE_Y_POS;
}
}
::SelectObject(hLocalDC, hOldBmp);
::DeleteDC(hLocalDC);
::DeleteObject(hBitmap);
return true;
Thoughts?

I have resolved my initial problem. Here are the steps I took:
Obtain the HDC using BeginPaint().
Obtain any additional information needed. For example, the dimension of the client area using GetClientRect().
Create a compatible DC using the function call CreateCompatibleDC().
Select your bitmap into the compatible DC; make sure you save the old bitmap returned by SelectObject().
Call StretchBlt() using the DC from BeginPaint() as destination and the compatible DC as source.
Select the old bitmap (obtained in step 4) back into the compatible DC using SelectObject().
Delete the compatible DC using DeleteDC().
Call EndPaint().

Related

Create a openGl context (new version)

i was trying to create a win32 that could handle openGl ( the new version). It doesnt seem to be mutch info about win32/opengl(new version, most examples are in the old version ) on the net.
The few info that i found lead me to this code. But it doesnt display the square.
Does any one know if this is the proper way to do it, and if so what is wrong with it(it doesnt display square).
Ps. i know that the part of the vbo, vao ,shader.. are working cause i already did that with sdl.
Thank a lot.... :)
Here is the Code:
#include <iostream>
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include <glew.h>
#include <wglew.h>
using namespace std;
void display(){
// display square
}
bool progRun = false;
//-------------------------------------------------------------------
//#####################################################################
//-------------------------------------------------------------------
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int CALLBACK WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
){
WNDCLASSEX wcex;
///////////////////////////LOAD GLEW///////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC | CS_DBLCLKS ;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = NULL;
if (!RegisterClassEx(&wcex))
{
MessageBox(NULL,"RegisterClassEx","ERROR",MB_OK|MB_ICONSTOP);
return 0;
}
HWND hWnd = CreateWindow(
szWindowClass,
szTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
500, 500,
NULL,
NULL,
hInstance,
NULL
);
if (!hWnd)
{
MessageBox(NULL,"hWnd","ERROR",MB_OK|MB_ICONSTOP);
return -1;
}
HDC hdc = GetDC(hWnd);
PIXELFORMATDESCRIPTOR pfd;
memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
pfd.nSize= sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
int pf = ChoosePixelFormat(hdc, &pfd);
if(pf == 0){
MessageBox(NULL,"pf == 0","ERROR",MB_OK|MB_ICONSTOP);
return -1;
}
if(SetPixelFormat(hdc, pf, &pfd) == false){
MessageBox(NULL,"SetPixelFormat","ERROR",MB_OK|MB_ICONSTOP);
return -1;
}
DescribePixelFormat(hdc, pf, sizeof(PIXELFORMATDESCRIPTOR), &pfd);
HGLRC hrc = wglCreateContext(hdc);
wglMakeCurrent(hdc, hrc);
glewExperimental = true;
if(glewInit() != GLEW_OK){
MessageBox(NULL, "Couldn't initialize GLEW!", "Fatal Error", MB_ICONERROR);
}
wglMakeCurrent(NULL, NULL);
ReleaseDC(hWnd, hdc);
wglDeleteContext(hrc);
DestroyWindow(hWnd);
///////////////////////////////TO_CREATE A OPENGL CONTEXT WITH LATER VERSION///////////////////////////////////////
//////////////////////////////////////////////////////////////////////
#define iMajorVersion 3
#define iMinorVersion 1
hWnd = CreateWindow(
szWindowClass,
szTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
500, 500,
NULL,
NULL,
hInstance,
NULL
);
if (!hWnd)
{
MessageBox(NULL,"hWnd","ERROR",MB_OK|MB_ICONSTOP);
return -1;
}
hdc = GetDC(hWnd);
bool bError = false;
if(iMajorVersion <= 2)
{
cout << "version 2" <<endl;
memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
pf = ChoosePixelFormat(hdc, &pfd);
if (pf == 0){
MessageBox(NULL,"pf == 0","ERROR",MB_OK|MB_ICONSTOP);
return false;
}
if(!SetPixelFormat(hdc, pf, &pfd)){
MessageBox(NULL,"SetPixelFormat 1","ERROR",MB_OK|MB_ICONSTOP);
return false;
}
// Create the old style context (OpenGL 2.1 and before)
hrc = wglCreateContext(hdc);
if(hrc)wglMakeCurrent(hdc, hrc);
else bError = true;
}
else if(WGLEW_ARB_create_context && WGLEW_ARB_pixel_format)
{
cout << "version 3" <<endl;
const int iPixelFormatAttribList[] =
{
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
WGL_COLOR_BITS_ARB, 32,
WGL_DEPTH_BITS_ARB, 24,
WGL_STENCIL_BITS_ARB, 8,
0 // End of attributes list
};
int iContextAttribs[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, iMajorVersion,
WGL_CONTEXT_MINOR_VERSION_ARB, iMinorVersion,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
0 // End of attributes list
};
int iNumFormats;
if(!wglChoosePixelFormatARB(hdc, iPixelFormatAttribList, NULL, 1, &pf, (UINT*)&iNumFormats)){
MessageBox(NULL,"wglChoosePixelFormatARB","ERROR",MB_OK|MB_ICONSTOP);
return 0;
}
// PFD seems to be only redundant parameter now
if(!SetPixelFormat(hdc, pf, &pfd)){
MessageBox(NULL,"SetPixelFormat 2","ERROR",MB_OK|MB_ICONSTOP);
return false;
}
hrc = wglCreateContextAttribsARB(hdc, 0, iContextAttribs);
// If everything went OK
if(hrc) wglMakeCurrent(hdc, hrc);
else bError = true;
//glewInit();
}else{
bError = true;
}
if(bError)
{
// Generate error messages
char sErrorMessage[255], sErrorTitle[255];
sprintf(sErrorMessage, "OpenGL %d.%d is not supported! Please download latest GPU drivers!", iMajorVersion, iMinorVersion);
sprintf(sErrorTitle, "OpenGL %d.%d Not Supported", iMajorVersion, iMinorVersion);
MessageBox(hWnd, sErrorMessage, sErrorTitle, MB_ICONINFORMATION);
return false;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
MSG msg;
progRun = true;
ShowWindow(hWnd,SW_SHOW);
UpdateWindow(hWnd);
//-----------Setup shader and objects
setupShader();
setupObject();
//-------
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL);
glClearColor(1,0,0,1);
while(progRun){
if (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
glClear(GL_COLOR_BUFFER_BIT);
display();
SwapBuffers(hdc);
}
return (int) msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
switch (message){
case WM_ERASEBKGND:
display();
break;
case WM_PAINT:
BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_SIZE:
glViewport(0, 0, LOWORD(lParam), HIWORD(lParam));
break;
case WM_DESTROY:
PostQuitMessage(0);
progRun = false;
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
break;
}
return 0;
}
If you use wglCreateContext then you get old context (<= 2.1).
You need wglCreateContextAttribsARB instead. But this first you need to get a pointer to this function, which requires using a context.
So:
Create a normal, old context, and set it current. Any pixelformat is
valid.
Get the pointers to wglCreateContextAttribsARB (and perhaps also for wglChoosePixelFormatARB), by using
wglGetProcAddress. Now you can delete the old context.
Set the pixelformat you wish and the context attributes you wish.
Create the context by that pointer.
Useful links from the wiki OpenGL are here and here and here

How do I implement double buffering in the winapi?

I can't stop the flickering. I got the advice to add dubbel-buffering. How do I do that?
#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
namespace {
const int ID_NEW = 1;
const int ID_QUIT = 2;
const int ID_ABOUT = 3;
const int NORTH_BUTTON_ID = 4;
const int SOUTH_BUTTON_ID = 5;
const int WEST_BUTTON_ID = 6;
const int EAST_BUTTON_ID = 7;
const int ID_FINISHED_GAME = 8;
int x = 0;
int y = 0;
int xStart = 0;
int yStart = 0;
int windowHeight = 400;
int windowWidth = 500;
char level1[20][21];
int noOfMoves = 0;
}
void readLevel(string fileName, char level[20][21]) {
char character{};
ifstream file(fileName);
int i = 0;
int j = 0;
if (file.is_open()) {
while (file >> character) {
level[j][i] = character;
if (level[j][i] == 's') {
y = yStart = j;
x = xStart = i;
}
if (++i % 20 == 0) {
i = 0;
j++;
}
}
file.close();
}
}
void restart(){
x = xStart;
y = yStart;
noOfMoves = 0;
}
LRESULT CALLBACK WinProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
HDC hdc{ 0 };
PAINTSTRUCT ps{ 0 };
switch (msg) {
case WM_CLOSE:
PostQuitMessage(0);
return 0;
case WM_COMMAND:
switch (LOWORD(wParam)){
case ID_ABOUT:
MessageBox(hwnd, L"About this program!", L"About", MB_OK);
return 0;
case ID_NEW:
restart();
return 0;
case ID_QUIT:
if (MessageBox(0, L"Do you really want to quit?", L"Are you sure?", MB_YESNO) == IDYES) {
PostQuitMessage(0);
return 0;
}
case NORTH_BUTTON_ID:
if (level1[y - 1][x] != '1') {
y -= 1;
noOfMoves++;
}
break;
case SOUTH_BUTTON_ID:
if (level1[y + 1][x] != '1'){
y += 1;
noOfMoves++;
}
break;
case WEST_BUTTON_ID:
if (level1[y][x - 1] != '1'){
x -= 1;
noOfMoves++;
}
break;
case EAST_BUTTON_ID:
if (level1[y][x + 1] != '1') {
x += 1;
noOfMoves++;
}
break;
}
if (level1[y][x] == 'e') {
wstring moves = L"Congratulations, you finished the game with " + to_wstring(noOfMoves);
MessageBox(hwnd, moves.c_str(), L"Finished game", MB_OK);
}
case WM_PAINT: {
char wall[2] = { "W" };
char floor[2] = { 'W' };
char current[2] = { "X" };
char goal[2] = { "G" };
wstring position = L"Position = [" + to_wstring(x) + L", " + to_wstring(y) + L"]";
wstring moves = L"Move = " + to_wstring(noOfMoves);
hdc = BeginPaint(hwnd, &ps);
TextOut(hdc, 20, 200, position.c_str(), position.size());
TextOut(hdc, 20, 220, moves.c_str(), moves.size());
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (level1[j][i] == '1') {
SetTextColor(hdc, RGB(0, 0, 0));
SetBkColor(hdc, RGB(0, 0, 0));
TextOut(hdc, 14 * i + 190, 14 * j + 20, LPCTSTR(wall), strlen(wall));
}
SetBkColor(hdc, RGB(255, 255, 255));
if (level1[j][i] == '0') {
SetTextColor(hdc, RGB(255, 255, 255));
TextOut(hdc, 14 * i + 190, 14 * j + 20, LPCTSTR(floor), strlen(floor));
}
SetTextColor(hdc, RGB(0, 0, 0));
if (i == x && j == y)
TextOut(hdc, 14 * i + 190, 14 * j + 20, LPCTSTR(current), strlen(current));
if (level1[j][i] == 'e')
TextOut(hdc, 14 * i + 190, 14 * j + 20, LPCTSTR(goal), strlen(goal));
}
}
EndPaint(hwnd, &ps);
break;
}
case WM_ERASEBKGND:
return true;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
HMENU CreateMainMenu() {
HMENU main = CreateMenu();
HMENU file = CreateMenu();
AppendMenu(file, MF_STRING, ID_NEW, L"&New");
AppendMenu(file, MF_SEPARATOR, 0, 0);
AppendMenu(file, MF_STRING, ID_QUIT, L"&Quit");
AppendMenu(main, MF_POPUP, (UINT_PTR)file, L"&File");
HMENU help = CreateMenu();
AppendMenu(help, MF_STRING, ID_ABOUT, L"&About");
AppendMenu(main, MF_POPUP, (UINT_PTR)help, L"&Help");
return main;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow) {
readLevel("level1.txt", level1);
WNDCLASS wc = { 0 };
wc.hbrBackground = NULL;
wc.lpfnWndProc = WinProc;
wc.hInstance = hInstance;
wc.lpszClassName = L"MyWindowClass";
RegisterClass(&wc);
HWND hwnd = CreateWindow(L"MyWindowClass", L"The Maze",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
windowWidth, windowHeight, 0, CreateMainMenu(), hInstance, 0);
HWND buttonNorth = CreateWindow(L"BUTTON", L"NORTH", WS_CHILD | WS_VISIBLE,
10, 20, 150, 40, hwnd, (HMENU)NORTH_BUTTON_ID, hInstance, 0);
HWND buttonSouth = CreateWindow(L"BUTTON", L"SOUTH", WS_CHILD | WS_VISIBLE,
10, 60, 150, 40, hwnd, (HMENU)SOUTH_BUTTON_ID, hInstance, 0);
HWND buttonEast = CreateWindow(L"BUTTON", L"EAST", WS_CHILD | WS_VISIBLE,
10, 140, 150, 40, hwnd, (HMENU)EAST_BUTTON_ID, hInstance, 0);
HWND buttonWest = CreateWindow(L"BUTTON", L"WEST", WS_CHILD | WS_VISIBLE,
10, 100, 150, 40, hwnd, (HMENU)WEST_BUTTON_ID, hInstance, 0);
UpdateWindow(hwnd);
ShowWindow(hwnd, nCmdShow);
MSG msg = { 0 };
BOOL isRunning = true;
while (isRunning) {
while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT)
isRunning = false;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
wc.hbrBackground = NULL;
InvalidateRect(hwnd, NULL, FALSE);
Sleep(10);
}
return 0;
}
As member Retired Ninja said, you make compatible device context with the original one ( hdc in your case ), and create a bitmap compatible with your original device context ( bitmap size is equal to the size of your rectangle where you paint your stuff ).
Then select this newly created bitmap into compatible device context you just created and draw everything on it.
Then you just BitBlt(...) the compatible device context into original one.
Do not forget to perform proper cleanup in order to avoid GDI leaks.
Your code should look like this:
case WM_PAINT:
{
// skipped the initialization part to preserve space
// just copy those, they are irrelevant for your problem
hdc = BeginPaint(hwnd, &ps);
// create memory DC and memory bitmap where we shall do our drawing
HDC memDC = CreateCompatibleDC( hdc );
// get window's client rectangle. We need this for bitmap creation.
RECT rcClientRectangle;
GetClientRect( hwnd, &rcClientRect );
// now we can create bitmap where we shall do our drawing
HBITMAP bmp = CreateCompatibleBitmap( hdc,
rcClientRect.right - rcClientRect.left,
rcClientRect.bottom - rcClientRect.top );
// we need to save original bitmap, and select it back when we are done,
// in order to avoid GDI leaks!
HBITMAP oldBmp = (HBITMAP)SelectObject( memDC, bmp );
// now you draw your stuff in memory dc;
// just substitute hdc with memDC in your drawing code,
// like I did below:
TextOut( memDC, //...
TextOut( memDC, //...
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (level1[j][i] == '1')
{
SetTextColor( memDC, //...
SetBkColor( memDC, //...
TextOut( memDC, //...
}
SetBkColor( memDC, //...
if (level1[j][i] == '0')
{
SetTextColor( memDC, //...
TextOut( memDC, //...
}
SetTextColor( memDC, //...
if (i == x && j == y)
TextOut( memDC, //...
if (level1[j][i] == 'e')
TextOut( memDC, //...
}
}
// OK, everything is drawn into memory DC,
// now is the time to draw that final result into our target DC
BitBlt( hdc, 0, 0, rcClientRect.right - rcClientRect.left,
rcClientRect.bottom - rcClientRect.top, memDC, 0, 0, SRCCOPY );
// all done, now we need to cleanup
SelectObject( memDC, oldBmp ); // select back original bitmap
DeleteObject( bmp ); // delete bitmap since it is no longer required
DeleteDC( memDC ); // delete memory DC since it is no longer required
EndPaint(hwnd, &ps);
break;
}

Getting error while creating CListCtrl

I'm trying to create a CListCtrl in MFC.
I am getting while making CImageList.
BOOL CRadioButtonTestDlg::InitImageList() {
mImageListNormal.Create(32, 32, ILC_COLOR32, 39, 1);
CString filePath;
CFileFind finder;
CString strWildcard(_T("E:\\MyAssignments\\Window system programming\\MFC\\sample_programs\\VContact\\res\\contact_images\\*.jpg"));
BOOL bWorking = finder.FindFile(strWildcard);
while (bWorking) {
bWorking = finder.FindNextFile();
if (finder.IsDots())
continue;
filePath = finder.GetFilePath();
CImage image;
CBitmap bitmap;
image.Load(filePath);
bitmap.Attach(image.Detach());
mImageListNormal.Add(&bitmap, RGB(255, 0, 255));
bitmap.DeleteObject();
}
finder.Close();
if(mAllContactListCtrl.SetImageList(&mImageListNormal, LVSIL_NORMAL) == NULL)
AfxMessageBox(_T("Falied to set ImageList"));
return TRUE;
}
call to mAllContactListCtrl.SetImageList() failed.
I want know whether using creating CBitmap from CImage is correct or I'm doing wrong some where else.
In the output I'm just getting string but not the Image.
=========================================================================
I am calling the above function from InitDialog()
BOOL CRadioButtonTestDlg::OnInitDialog() {
CDialog::OnInitDialog();
CRect rect;
mAllContactListCtrl.GetClientRect(&rect);
mAllContactListCtrl.InsertColumn(0, _T("Name"), LVCFMT_LEFT, rect.Width()-15, 0);
for (int i = 0; i < 39; i++) {
mAllContactListCtrl.InsertItem(i, _T("Some String"), i);
}
InitImageList();
return TRUE;
}

How Do I Create a 32-bit Tray Icon With Transparency (using GDI)?

I'm trying to create an icon that displays a piece of text in the system tray. (Obviously, it won't be longer than a couple of characters.)
So far I've tried:
#include <tchar.h>
#include <Windows.h>
#include <Windowsx.h>
static HICON CreateIcon(LPCTSTR txt) {
HICON hIcon = NULL;
HDC hDC = NULL; {
HDC hDCScreen = GetDC(NULL);
if (hDCScreen != NULL) {
__try { hDC = CreateCompatibleDC(hDCScreen); }
__finally { ReleaseDC(NULL, hDCScreen); }
}
}
if (hDC != NULL) {
__try {
HFONT hFont = CreateFontIndirect(&ncm.lfMessageFont);
if (hFont != NULL) {
__try { SelectFont(hDC, hFont); }
__finally { DeleteFont(hFont); }
}
int width = GetSystemMetrics(SM_CXSMICON),
height = GetSystemMetrics(SM_CYSMICON);
HBITMAP hBmp = CreateCompatibleBitmap(hDC, width, height);
if (hBmp != NULL) {
__try {
HBITMAP hMonoBmp =
CreateCompatibleBitmap(hDC, width, height);
if (hMonoBmp != NULL) {
__try {
RECT rect = { 0, 0, width, height };
HGDIOBJ prev = SelectObject(hDC, hBmp);
__try {
SetBkMode(hDC, TRANSPARENT);
SetTextColor(hDC, RGB(255, 255, 255));
ICONINFO ii = { TRUE, 0, 0, hMonoBmp, hBmp };
int textHeight =
DrawText(hDC, txt, _tcslen(txt), &rect, 0);
if (textHeight != 0) {
hIcon = CreateIconIndirect(&ii);
}
} __finally { SelectObject(hDC, prev); }
} __finally { DeleteObject(hMonoBmp); }
}
} __finally { DeleteObject(hBmp); }
}
} __finally { DeleteDC(hDC); }
}
return hIcon;
}
with this code:
static void _tmain(int argc, TCHAR* argv[]) {
HICON hIcon = CreateIcon(_T("Hi"));
if (hIcon != NULL) {
__try {
NOTIFYICONDATA nid = { sizeof(nid) };
nid.hWnd = GetConsoleWindow();
BOOL success = Shell_NotifyIcon(NIM_ADD, &nid);
if (success) {
nid.uFlags = NIF_ICON;
nid.hIcon = hIcon;
success = Shell_NotifyIcon(NIM_MODIFY, &nid);
}
} __finally { DestroyIcon(hIcon); }
}
}
but all I get is a monochrome bitmap that says Hi in white text on a black background. (If I change the RGB(255, 255, 255) even slightly, say to RGB(255, 255, 254), it becomes black, so it's monochrome.)
Any ideas?
(*Note: I'm not looking for MFC, ATL, or any other library solutions, just Win32/GDI calls.)
Edit:
Here's what it looks like currently:
If I recall correctly, a partially transparent icon (which I think is what want) has a monochrome bitmap for its mask. This mask happens to be ignored but you still have to supply it. You aren't creating a monochrome bitmap, you appear to be creating a 32bpp bitmap. I also don't see anywhere where you initialise the alpha values for you main bitmap so that the areas which you don't write to are transparent.
An example with code is provided here: How To Create an Alpha Blended Cursor or Icon in Windows XP

DirectX Texture Warping

I am writing a WIN32 DirectX 9 program in which I load a few textures (a person and a background) and display them on the screen. However, they become warped (stretched), not being a one-to-one representation of what I drew in Paint. I tried different window sizes and different screen resolutions, but it still doesn't work.
I can force a very close imitation of the original thing by calling D3DXMatrixTransformation2D before drawing the sprite. However, that doesn't fix the problem. My program relies on me knowing exactly where the person is in relevence to the background (in reality, the background moves and the person stays in the middle of the screen).
Is there something simple I am missing or is it that I just can't do that for some reason? I can give code if it more than a simple fix, but I hope not. For the record, I recieve no errors or warnings; it's just a visual and movement-tracking issue. Thank you.
EDIT: Here's some code:
//start of program
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
//Define and register the Windows Class ***Function
createWindowClass(hInstance);
//Create the window (still not shown)
HWND hWnd = CreateWindow("Sample Window Class", "Person With Ship", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, hInstance, NULL);
//Define and create the DirectX9 object ***Function
HRESULT hr = createDirectX(hWnd);
D3DXCreateSprite(d3dDevice, &sprite);
D3DXCreateTextureFromFile(d3dDevice, "landingPad2.png", &texture);
D3DXCreateTextureFromFile(d3dDevice, "person.png", &person);
//D3DXCreateTextureFromFile(d3dDevice, "secondRoom.png", &secondRoom);
//Set up text
LPD3DXFONT mFont;
D3DXCreateFont(d3dDevice, 20, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Arial"), &mFont );
//Finally show window
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
//setup keyboard
RAWINPUTDEVICE Rid[1]; // array of structs for input devices
Rid[0].usUsagePage = 1; // use 1 for most inputs
Rid[0].usUsage = 6; //2-mouse, 4-joystick, 6-keyboard
Rid[0].dwFlags = 0; //use 0
Rid[0].hwndTarget=NULL; //use NULL
RegisterRawInputDevices(Rid,1,sizeof(RAWINPUTDEVICE)); // registers all of the input devices
//MAIN LOOP!!
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message!=WM_QUIT)
{
while(PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
updateGraphics(hr, mFont);
updatePosition();
}
mFont->Release();
texture->Release();
return msg.wParam;
}
void createWindowClass(HINSTANCE hInstance)
{
const LPCSTR CLASS_NAME = "Sample Window Class";
//create windows object
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style= CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc= (WNDPROC)WndProc;
wcex.cbClsExtra= 0;
wcex.cbWndExtra= 0;
wcex.hInstance= hInstance;
wcex.hIcon= 0;
wcex.hCursor= LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground= (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName= 0;
wcex.lpszClassName= CLASS_NAME;
wcex.hIconSm= 0;
//register windows class
RegisterClassEx(&wcex);
}
HRESULT createDirectX(HWND hWnd)
{
//create directx object
d3dObject = Direct3DCreate9(D3D_SDK_VERSION);
if (d3dObject==NULL)
{
exit(1);
}
//Present Parameters struct
D3DPRESENT_PARAMETERS presParams;
//Sets everything to 0
ZeroMemory(&presParams, sizeof(presParams));
presParams.Windowed = TRUE;
presParams.SwapEffect = D3DSWAPEFFECT_DISCARD;
presParams.BackBufferFormat = D3DFMT_UNKNOWN;
presParams.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
//DIRECT3D Stuff (not used currently)
//presParams.EnableAutoDepthStencil = TRUE;
//presParams.AutoDepthStencilFormat = D3DFMT_D16;
//d3dDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
//D3DXMatrixIdentity( &worldMatrix );
HRESULT hr = d3dObject->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL,hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &presParams, &d3dDevice);
return hr;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INPUT:
{
UINT bufferSize;
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &bufferSize, sizeof (RAWINPUTHEADER));
// Create a buffer of the correct size
BYTE *buffer=new BYTE[bufferSize];
// Call the function again, this time with the buffer to get the data
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, (LPVOID)buffer, &bufferSize, sizeof (RAWINPUTHEADER));
PRAWINPUT raw = (RAWINPUT*) buffer;
getInput(raw);
break;
}
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
int wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_EXIT:
DestroyWindow(hWnd);
break;
}
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
void getInput(PRAWINPUT raw)
{
if (raw->header.dwType== RIM_TYPEKEYBOARD)
{
USHORT keyCode = raw->data.keyboard.VKey;
switch(keyCode)
{
case VK_LEFT:
keyUp=raw->data.keyboard.Flags & RI_KEY_BREAK;
if (keyUp == false)
counterTrue = true;
else
counterTrue = false;
break;
case VK_RIGHT:
keyUp=raw->data.keyboard.Flags & RI_KEY_BREAK;
if (keyUp == false)
clockwiseTrue = true;
else
clockwiseTrue = false;
break;
case VK_UP:
keyUp=raw->data.keyboard.Flags & RI_KEY_BREAK;
if (keyUp == false)
upTrue = true;
else
upTrue = false;
break;
case VK_DOWN:
keyUp=raw->data.keyboard.Flags & RI_KEY_BREAK;
if (keyUp == false)
downTrue = true;
else
downTrue = false;
break;
default:
break;
}
if (keyCode == 'A')
{
keyUp=raw->data.keyboard.Flags & RI_KEY_BREAK;
if (keyUp == false)
leftTrue = true;
else
leftTrue = false;
}
if (keyCode == 'D')
{
keyUp=raw->data.keyboard.Flags & RI_KEY_BREAK;
if (keyUp == false)
rightTrue = true;
else
rightTrue = false;
}
if (keyCode == 'W')
{
keyUp=raw->data.keyboard.Flags & RI_KEY_BREAK;
if (keyUp == false)
upTrue = true;
else
upTrue = false;
}
if (keyCode == 'S')
{
keyUp=raw->data.keyboard.Flags & RI_KEY_BREAK;
if (keyUp == false)
downTrue = true;
else
downTrue = false;
}
}
}
void updateGraphics(HRESULT hr, LPD3DXFONT mFont)
{
hr = d3dDevice->Clear(0, NULL, D3DCLEAR_TARGET| D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
hr = d3dDevice->BeginScene();
sprite->Begin(D3DXSPRITE_ALPHABLEND);
// Texture being used is 64 by 64:
D3DXVECTOR2 spriteCentre=D3DXVECTOR2(rotationCenter.x, rotationCenter.y);
// Screen position of the sprite
D3DXVECTOR2 trans=D3DXVECTOR2(pos.x, pos.y);
// Build our matrix to rotate, scale and position our sprite
D3DXMATRIX mat;
D3DXVECTOR2 scaling(0.5798f, 0.784f);
// out, scaling centre, scaling rotation, scaling, rotation centre, rotation, translation
D3DXMatrixTransformation2D(&mat,NULL, NULL, &scaling,&spriteCentre,rotation,NULL/*&trans*/);
// Tell the sprite about the matrix
sprite->SetTransform(&mat);
sprite->Draw(texture, NULL, &rotationCenter, &pos, 0xFFFFFFFF);
scaling.x = 0.53;
scaling.y = 0.57f;
D3DXMatrixTransformation2D(&mat,NULL,0.0, &scaling,&spriteCentre, 0,NULL/*&trans*/);
sprite->SetTransform(&mat);
sprite->Draw(person, NULL, NULL, &personPos, 0xFFFFFFFF);
sprite->End();
DisplaySomeText(mFont);
d3dDevice->EndScene();
d3dDevice->Present(NULL, NULL, NULL, NULL);
}
void updatePosition()
{
if (clockwiseTrue == true)
{
rotation -= (float)0.03;
}
else if (counterTrue == true)
{
rotation += (float)0.03;
}
if (rotation >(PI))
{
rotation -= (float)(2*PI);
}
if (rotation <= -(PI))
{
rotation += (float)(2*PI);
}
if (upTrue == true)
{
pos.y += (3*cos(rotation));
pos.x += (3*sin(rotation));
}
else if (downTrue == true)
{
pos.y -= (3*cos(rotation));
pos.x -= (3*sin(rotation));
}
if (leftTrue == true)
{
pos.x += (3*cos(rotation));
pos.y -= (3*sin(rotation));
}
else if (rightTrue == true)
{
pos.x -= (3*cos(rotation));
pos.y += (3*sin(rotation));
}
//collision detection
if (rotation >=0 && rotation < (PI/2))
{
if (pos.y - (30*cos(rotation)) - (30*sin(rotation)) < -138 && pos.x < 350 && pos.x > -550)
{
pos.y = -142 + (30*cos(rotation)) + (30*sin(rotation));
}
}
if (rotation < 0 && rotation > -(PI/2))
{
if (pos.y - (51*cos(rotation)) + (14*sin(rotation)) < -142 && pos.x < 350 && pos.x > -550)
{
pos.y = -142 + (51*cos(rotation)) - (14*sin(rotation));
}
}
if (rotation < -(PI/2) && rotation > -(PI))
{
if (pos.y + (51*cos(rotation)) + (14*sin(rotation)) < -142 && pos.x < 350 && pos.x > -550)
{
pos.y = -142 - (51*cos(rotation)) - (14*sin(rotation));
}
}
if (rotation > (PI/2) && rotation <= (PI))
{
if (pos.y + (51*cos(rotation)) - (14*sin(rotation)) < -142 && pos.x < 350 && pos.x > -550)
{
pos.y = -142 - (51*cos(rotation)) + (14*sin(rotation));
}
}
}
void DisplaySomeText(LPD3DXFONT mFont)
{
// Create a colour for the text - in this case blue
D3DCOLOR fontColor = D3DCOLOR_ARGB(255,0,0,255);
// Create a rectangle to indicate where on the screen it should be drawn
RECT rct;
rct.left=200;
rct.right=780;
rct.top=10;
rct.bottom=rct.top+20;
TCHAR cX[30] = "x";
TCHAR cY[30] = "y";
TCHAR cR[30] = "r";
TCHAR cQ[30] = "q";
size_t cchDest = 30;
LPCTSTR pszFormat = TEXT("%f");
HRESULT har = StringCchPrintf(cX, cchDest, pszFormat, pos.x);
HRESULT her = StringCchPrintf(cY, cchDest, pszFormat, pos.y);
HRESULT hir = StringCchPrintf(cR, cchDest, pszFormat, rotation);
HRESULT hur = StringCchPrintf(cQ, cchDest, pszFormat, (pos.y - (43*cos(rotation))));
mFont->DrawText(NULL, cX, -1, &rct, 0, fontColor);
rct.left += 100;
mFont->DrawText(NULL, cY, -1, &rct, 0, fontColor);
rct.left += 100;
mFont->DrawText(NULL, cR, -1, &rct, 0, fontColor);
rct.left += 100;
mFont->DrawText(NULL, cQ, -1, &rct, 0, fontColor);
}
So, finally: the issue was due to the texture dimensions not being powers of two :) This behaviour is quite usual, but it is still hardware-dependent: in theory there may exist some videocards which handle arbitrary texture sizes the same way as power-of-two-sized ones. To know that they do we'd have to check their capabilities via IDirect3DDevice9::GetDeviceCaps.

Resources