Getting a/d converter example program to work in a C++ windows program - c++

I got the following example code for a C windows programm from the developer of my analog to digital converter and want to make it run as a windows c++ project in Visual Studio 2016.
As a beginner in C++, windows API and this universal library for the converter I'm overwhelmed with the troubleshooting right now. The plan was to learn by making the code work but right now it's really hard to find out where the problems are and there's not the time to learn everything from scratch (though I try next to it)
This is my setup: Windows 7 64bit, MS Visual Studio Community 2017, USB 1608fs plus a/d converter with its universal library
These are the errors I'm currently getting:
a value of type "HANDLE" cannot be used to initialize an entity of type "HINSTANCE" (row 83)
a value of type "HGDIOBJ" cannot be used to initialize an entity of type "HBRUSH"(row 86)
the argument of type "HANDLE" is incompatible with parameter type "HINSTANCE" (row 93)
Actions I took until now:
creating a new empty win32 project in MS Visual Studio
copying the example code
copying the header file and the library from the converter into the same folder
switching the character set from unicode to multibyte
switching off the precompiled header
include the missing headers from the precompiled header
Here is the code:
#include <windows.h> /* Compiler's include files's */
#include <string.h>
#include <stdio.h>
#include "cbw.h" /* Universal Library's include file */
#include "targetver.h"
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#define BOARD_NUM 0 /* Number of A/D board as defined with InstaCal */
#define ADRANGE BIP5VOLTS /* A/D voltage range */
#define TIMER_NUM 1 /* Windows timer used by this program */
HWND hWndMain; /* handle for main window */
LONG FAR PASCAL MainMessageHandler(HWND, UINT, WPARAM, LPARAM);
/************************************************************************
*
* Name: WinMain
*
* Arguments: hInstance - the instance handle for the program
* hPrevInstance - the class name of the application (not used)
* CmndLine - command line was called with (not used)
* CmndShow - indicates how to display window
*
* This is the entry point to the program. It gets called by Windows
* to start the program up. This routine creates the main window,
* initializes a timer, and then falls into the main Windows Get
* message/Dispatch message loop.
*
************************************************************************/
int PASCAL
WinMain(HANDLE hInstance, HANDLE hPrevInstance, LPSTR CmdLine, int nCmdShow)
{
MSG msg; /* MSG structure to pass to windows proc */
WNDCLASS wndclass;
char *AppName; /* Name for the window */
cbErrHandling(PRINTALL, STOPALL); /* Set library's error handling */
CmdLine = NULL; /* Not used */
AppName = "WINCDEMO"; /* The name of this application */
if (!hPrevInstance)
{
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = MainMessageHandler;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(hInstance, AppName);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = AppName;
wndclass.lpszClassName = AppName;
RegisterClass(&wndclass);
}
/* create application's Main window */
hWndMain = CreateWindow(AppName, /* Window class name */
"AIn Demo",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, /* Use default X, Y */
CW_USEDEFAULT, /* Use default X, Y */
GetSystemMetrics(SM_CXSIZE) * 12, /* x - fit text */
GetSystemMetrics(SM_CYSIZE) * 10, /* y - fit text */
NULL, /* Parent window's handle */
NULL, /* Default to Class Menu */
hInstance, /* Instance of window */
NULL); /* Create struct for WM_CREATE */
if (hWndMain == NULL)
{
MessageBox(NULL, "Could not create window in WinMain", NULL, MB_ICONEXCLAMATION);
return (1);
}
ShowWindow(hWndMain, nCmdShow); /* Display main window */
UpdateWindow(hWndMain);
// /* Start a 500ms timer to update display */
if (!SetTimer(hWndMain, TIMER_NUM, 50, NULL))
{
MessageBox(NULL, "Error starting Windows timer", NULL, MB_OK |
MB_ICONEXCLAMATION);
return (1);
}
while (GetMessage(&msg, NULL, 0, 0)) /* Main message loop */
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnregisterClass(AppName, hInstance);
return (msg.wParam);
}
/************************************************************************
*
* Name: MainMessageHandler
*
* Arguments: hWnd - handle to the window
* Message - message that needs to be handled
* hParam - message parameter
* lParam - message parameter
*
* This is the message dispatcher that gets called whenever Windows
* sends a message to this window. WinMain started up a timer that
* sends a message every 1/2 sec. When the message (WM_TIMER)is received
* by this routine, it reads the A/D.
* It also causes a screen update which will automatically generate a
* WM_PAINT message. The WM_PAINT handler takes care of converting the
* raw A/D values to voltages and printing them in the Window.
*
************************************************************************/
LONG FAR PASCAL
MainMessageHandler(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam)
{
HDC hDC; /* handle for the display device */
PAINTSTRUCT ps; /* holds PAINT information */
TEXTMETRIC tm; /* holds TEXT information */
static HRGN hRgn; /* Rectangle region Handles */
static int CharWidth, CharHeight;
static unsigned short DataVal;
int x, y;
char OutString[80], *str;
float Voltage;
switch (Message) /* Windows Message Loop */
{
case WM_CREATE:
hDC = GetDC(hWndMain); /* Get the device context for window */
GetTextMetrics(hDC, &tm); /* From context, get size of font */
CharWidth = tm.tmAveCharWidth;
CharHeight = tm.tmHeight + tm.tmExternalLeading;
ReleaseDC(hWndMain, hDC);
hRgn = CreateRectRgn(0, 0, CharWidth * 30, CharHeight * 12);
break;
case WM_TIMER: /* All Timer Events Processed Here */
InvalidateRgn(hWndMain, hRgn, FALSE); /* Force screen update */
break;
case WM_PAINT: /* Repaint client area of window */
hDC = BeginPaint(hWndMain, &ps);
x = CharWidth * 2; /* Position cursor within window */
y = CharHeight; /* One line down and 2 chars in */
str = " A/D Info"; /* Print title */
TextOut(hDC, x, y, str, strlen(str));
y += CharHeight; /* Print current index */
cbAIn(BOARD_NUM, 0, ADRANGE, &DataVal);
y += CharHeight * 2; /* Print raw data value */
sprintf(OutString, "Raw A/D value = %u ", DataVal);
TextOut(hDC, x, y, OutString, strlen(OutString));
y += CharHeight; /* Convert raw A/D to volts and print */
cbToEngUnits(BOARD_NUM, ADRANGE, DataVal, &Voltage);
sprintf(OutString, "Voltage = %.2f ", Voltage);
TextOut(hDC, x, y, OutString, strlen(OutString));
SetTextAlign(hDC, TA_LEFT | TA_TOP);
EndPaint(hWndMain, &ps);
break;
case WM_CLOSE: /* Close the window */
DestroyWindow(hWnd);
if (hWnd == hWndMain)
PostQuitMessage(0); /* Send message to Quit application */
break;
default:
return (DefWindowProc(hWnd, Message, wParam, lParam));
}
return (0l);
}

Instead of randomly roaming around copypasting staff and switching things on and off you should first understand the errors you are facing. For example first error: You should lookup on MSDN what HANDLE and HINSTANCE are and figure out where are you getting them from. You get hInstance from WinMain. You should lookup on MSDN for WinMain and figure out that signature you used is somewhat wrong and you are supposed to use
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow
)
So the error with wndclass.hInstance = hInstance; assignment of HANDLE to HINSTANCE should be gone (assuming that I've pointed the correct line of this error because you only specified row).
And so on.

Related

C++ changing image on user input in WinAPI

I am having issues in getting my .bmp image displayed to change to another one on user input. The image can be successfully printed at the start (title.bmp), but is supposed to change when pressing 1 or 2 followed by enter (to introduction.bmp & start.bmp). I must be missing something!
Where this happens is around the bottom of the code from while (running == 1) { so skip down to there.
I am using loadImage("title.bmp"); to print my images (I change the filename appropriately of course), and cin >> menuSelection; to pause the program and wait until the user presses one or two followed by enter.
I've searched many, many pages on how to print and change images in WinAPI, and this is the closest I can get. If there is any other information I have missed please tell me and I will comment it. Thanks in advance for helping!
//These are the libraries (external files) to include at the start.
#include <cstdio>
#include <windows.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
using namespace std;
//Defining the [global] variables that will be used throughout the program
int running = 1;
int menuSelection = 0;
int userInput;
int userInputDummy;
int intPointer;
//Starter variables used in creating a window and printing images. These are global.
HDC imageDC; // the DC to hold our image
HBITMAP imageBmp; // the actual bitmap which contains the image (will be put in the DC)
HBITMAP imageBmpOld; // the DC's old bitmap (for cleanup)
const int screenSize_X = 640;
const int screenSize_Y = 480;
//Functions! Sections of code to re-used in the program
// Function to load the image into our DC so we can draw it to the screen
void loadImage(const char* pathname)
{
imageDC = CreateCompatibleDC(NULL); // create an offscreen DC
imageBmp = (HBITMAP)LoadImageA( // load the bitmap from a file
NULL, // not loading from a module, so this is NULL
pathname, // the path we're loading from
IMAGE_BITMAP, // we are loading a bitmap
0, 0, // don't need to specify width/height
LR_DEFAULTSIZE | LR_LOADFROMFILE// use the default bitmap size (whatever the file is), and load it from a file
);
imageBmpOld = (HBITMAP)SelectObject(imageDC, imageBmp); // put the loaded image into our DC
}
// Function to clean up
void cleanUpImage()
{
SelectObject(imageDC, imageBmpOld); // put the old bmp back in our DC
DeleteObject(imageBmp); // delete the bmp we loaded
DeleteDC(imageDC); // delete the DC we created
}
// The function to draw our image to the display (the given DC is the screen DC)
void drawImage(HDC screen)
{
BitBlt(
screen, // tell it we want to draw to the screen
0, 0, // as position 0,0 (upper-left corner)
screenSize_X, // width of the rect to draw
screenSize_Y, // height of the rect
imageDC, // the DC to get the rect from (our image DC)
0, 0, // take it from position 0,0 in the image DC
SRCCOPY // tell it to do a pixel-by-pixel copy
);
}
// A callback to handle Windows messages as they happen
LRESULT CALLBACK wndProc(HWND wnd, UINT msg, WPARAM w, LPARAM l)
{
// what kind of message is this?
switch (msg)
{
// we are interested in WM_PAINT, as that is how we draw
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC screen = BeginPaint(wnd, &ps); // Get the screen DC
drawImage(screen); // draw our image to our screen DC
EndPaint(wnd, &ps); // clean up
}break;
// we are also interested in the WM_DESTROY message, as that lets us know when to close the window
case WM_DESTROY:
PostQuitMessage(0);
break;
}
// for everything else, let the default window message handler do its thing
return DefWindowProc(wnd, msg, w, l);
}
// A function to create the window and get it set up
HWND createWindow(HINSTANCE inst)
{
WNDCLASSEX wc = { 0 }; // create a WNDCLASSEX struct and zero it
wc.cbSize = sizeof(WNDCLASSEX); // tell windows the size of this struct
wc.hCursor = LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW)); // tell it to use the normal arrow cursor for this window
wc.hInstance = inst; // give it our program instance
wc.lpfnWndProc = wndProc; // tell it to use our wndProc function to handle messages
wc.lpszClassName = TEXT("DisplayImage"); // give this window class a name.
RegisterClassEx(&wc); // register our window class with Windows
// the style of the window we want... we want a normal window but do not want it resizable.
int style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU; // normal overlapped window with a caption and a system menu (the X to close)
// Figure out how big we need to make the window so that the CLIENT area (the part we will be drawing to) is
// the desired size
RECT rc = { 0,0,screenSize_X,screenSize_Y }; // desired rect
AdjustWindowRect(&rc, style, FALSE); // adjust the rect with the given style, FALSE because there is no menu
return CreateWindow( // create the window
TEXT("DisplayImage"), // the name of the window class to use for this window (the one we just registered)
TEXT("Display an Image"), // the text to appear on the title of the window
style | WS_VISIBLE, // the style of this window (OR it with WS_VISIBLE so it actually becomes visible immediately)
100, 100, // create it at position 100,100
rc.right - rc.left, // width of the window we want
rc.bottom - rc.top, // height of the window
NULL, NULL, // no parent window, no menu
inst, // our program instance
NULL); // no extra parameter
}
//||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
// _________________________________________________________________________________________
// The actual entry point for the program!
// This is Windows' version of the 'main' function:
int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmd, int show)
{
// load our image
loadImage("title.bmp");
// create our window
HWND wnd = createWindow(inst);
// Do the message pump! keep polling for messages (and respond to them)
// until the user closes the window.
MSG msg;
while (GetMessage(&msg, wnd, 0, 0)) // while we are getting non-WM_QUIT messages...
TranslateMessage(&msg); // translate them
DispatchMessage(&msg); // and dispatch them (our wndProc will process them)
{
while (running == 1) {
//Welcoming the user to the program, and asking them what they want to do (starts functions)
cin >> menuSelection;
//Selecting the introduction option
if (menuSelection == 1) {
loadImage("introduction.bmp");
cin >> userInputDummy;
menuSelection = 0;
}
//Selecting the start option
else if (menuSelection == 2) {
loadImage("start");
cin >> userInputDummy;
menuSelection = 0;
}
//Selecting the exit option
else if (menuSelection == 3) {
menuSelection = 0;
running = 0;
}
}
// once the user quits....
cleanUpImage();
return 0;
return EXIT_SUCCESS;
}
}
you cannot use cin in win32 use an editbox then get the user's input from it as character string then if you want convert it to an integer value otherwise use the API:
GetDlgItemInt(...);
you are also handling only GetMessage in while-loop while you only handle dispatchmessage outside the loop which means you handle it only once, when getmessage fails (the end of program) so the result is a freezing windows as long as there's no one who takes messages from getmessage to the target windo.
the solution: make DispatchMessage inside while loop:
another thing: you pass hwnd to getmessage the result destroying the window won't make the application exit.
take a look at GetMessage() when passing a non-null value:
link text
the correct thing in your case:
while (GetMessage(&msg, 0, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
* don't load image inside loop just load at the time wanted:
make an edit box with style ES_NUMBER and another button names for example change image so when clicked take the content of edit box convert it to integer, check whether it is 1 or 2 then load imaged depending the value.
you may ask "why I can't use iostream input and output streams in win32" because I ask you "where is console windows?" and if it is here what is the role of while-loop (blocking waiting for messages)?

Weird array behavior in classes along with Windows DCs (C++)?

I'm working on creating a text based Windows game, and I am having a problem (I guess) with arrays not working the same within a class scope as within the main function. As far as I can tell it is some kind of interaction between a larger array class member (or large total amount of variables) and Windows creating a DC or other Windows API calls and/or variables.
What I want to do is a have a class called Map that contains a two dimensional array of Tiles. Tile is just a simple struct with basic tile information. I would like to make the array 256 x 256. This shouldn't be a problem as far as I can figure. Each Tile should be 32 bytes. That's 2 MB total for the array.
However, the game crashes when I declare a variable of the Map class in the main function, and then do things with Windows DCs. The return value seems to vary, In the current form, it usually returns 255, but I have also gotten "process terminated with status -1073741571". A 128 x 128 array does work in the class though. It also works fine if I remove either the array or the code in DisplayScreen. And as I implied, it also works if I just move the array of Tiles to the main function.
I'm honestly baffled. I have no idea what the difference would be. Nothing is going out of scope. Doesn't matter if it is a public or private member. Non dynamic class members should all get declared on the stack and it shouldn't work any differently in a class versus otherwise, right?
For other information, I am using Code::Blocks with the Min GW compiler. Everything is up to date. I am running Windows 10. My computer specs shouldn't be an issue either, but if it matters, I have 16 GB memory and a 4Ghz Athlon FX 8 core processor.
Edit: Here is the full code, so nothing is left out
Game.h:
#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
struct Tile
{
char chr[2];
int r[2], b[2], g[2];
bool solid;
bool translucent;
int opacity;
};
class Map
{
Tile tileMap[256][256];
public:
Map();
};
Map::Map()
{
int i, j;
for(i=0;i<256;i++)
{
for(j=0;j<256;j++)
{
tileMap[i][j].chr[0] = 'X';
tileMap[i][j].b[0] = 255;
tileMap[i][j].r[0] = 255;
tileMap[i][j].g[0] = 255;
tileMap[i][j].chr[1] = ' ';
tileMap[i][j].b[1] = 0;
tileMap[i][j].r[1] = 0;
tileMap[i][j].g[1] = 0;
tileMap[i][j].solid = false;
tileMap[i][j].translucent = false;
tileMap[i][j].opacity = 255;
}
}
}
main.cpp:
#include <windows.h>
#include "Game.h"
#define FRAMERATE 60
//Function declarations
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
void DisplayScreen(HWND pWnd, Map &pMap);
//Make the class name into a global variable
char strClassName[ ] = "GameApp";
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpstrArgument,
int nCmdShow)
{
HWND hWnd; //This is the handle for our window
MSG messages; //Here messages to the application are saved
WNDCLASSEX wndClassEx; //Data structure for the windowclass
Map test;
DWORD sysTimer;
DWORD sysPrevTime = 0;
DWORD timerDelta = 1000 / FRAMERATE;
//Get a handle for the whole screen
HDC hDC = GetDC(NULL);
//Initalize the Window structure
wndClassEx.hInstance = hThisInstance;
wndClassEx.lpszClassName = strClassName;
wndClassEx.lpfnWndProc = WindowProcedure;
wndClassEx.style = CS_DBLCLKS;
wndClassEx.cbSize = sizeof (WNDCLASSEX);
wndClassEx.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wndClassEx.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wndClassEx.hCursor = LoadCursor (NULL, IDC_ARROW);
wndClassEx.lpszMenuName = NULL; //No menu
wndClassEx.cbClsExtra = 0;
wndClassEx.cbWndExtra = 0;
wndClassEx.hbrBackground = CreateSolidBrush(RGB(0,0,0));
//Register the window class, and if it fails quit the program
if (!RegisterClassEx (&wndClassEx))
return 0;
//Create Window with registered window class
hWnd = CreateWindowEx (
0,
strClassName, //Class name
"Game Test", //Title Text
WS_OVERLAPPEDWINDOW, //default window type
0, //X pos of window at top left
0, //Y pos of window at top left
GetDeviceCaps(hDC, HORZRES), //Set window width to screen width
GetDeviceCaps(hDC, VERTRES), //Set window height to screen height
HWND_DESKTOP, //Child-window to desktop
NULL, //No menu
hThisInstance, //Program Instance handler
NULL); //No Window Creation data
//Removes borders from the window
SetWindowLong(hWnd, GWL_STYLE, WS_POPUP);
//Make the window visible on the screen
ShowWindow (hWnd, nCmdShow);
//Run the message and game loop
while (true)
{
while(PeekMessage(&messages,NULL,0,0, PM_REMOVE))
{
if (messages.message == WM_QUIT)
{
ReleaseDC(NULL, hDC);
DestroyWindow(hWnd);
return 0;
}
TranslateMessage(&messages);
DispatchMessage(&messages);
}
sysTimer = timeGetTime();
if (sysTimer >= (sysPrevTime + timerDelta) )
{
sysPrevTime = sysTimer;
DisplayScreen(hWnd, test);
}
}
}
//This function is called by the Windows function DispatchMessage()
LRESULT CALLBACK WindowProcedure (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage (0); //Send WM_QUIT to the message queue
break;
default:
return DefWindowProc (hWnd, message, wParam, lParam);
}
return 0;
}
void DisplayScreen(HWND pWnd, Map &pMap)
{
HDC hDC = GetWindowDC(pWnd);
HDC hdcBuf = CreateCompatibleDC(hDC);
HBITMAP hbmBuf = CreateCompatibleBitmap(hDC, 800, 600);
HFONT hMapFont = CreateFont(17,11,0,0,400,FALSE,FALSE,FALSE,ANSI_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,ANTIALIASED_QUALITY,DEFAULT_PITCH | FF_MODERN,"Lucida Console");
HFONT hTxtFont = CreateFont(17,11,0,0,400,FALSE,FALSE,FALSE,ANSI_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,ANTIALIASED_QUALITY,DEFAULT_PITCH | FF_MODERN,"Lucida Console");
SelectObject(hdcBuf, hbmBuf);
SelectObject(hdcBuf, hMapFont);
SetBkColor(hdcBuf, RGB(0,0,0));
SetTextColor(hdcBuf, RGB(255,255,255));
//Draw to the buffer
TextOut(hdcBuf, 10, 10, "Hello World #", 15);
//Tranfers the buffer to the Screen
BitBlt(hDC, 100, 100, 800, 600, hdcBuf, 0, 0, SRCCOPY);
//Release all object handles
DeleteObject(hTxtFont);
DeleteObject(hMapFont);
DeleteObject(hbmBuf);
DeleteDC(hdcBuf);
ReleaseDC(pWnd, hDC);
}
It crashes with even one instance of something creating a DC. It works fine otherwise creating and destroying the DCs and displaying the bitmap over and over again even if I leave it for an hour. Once I create that class with the large array in it though, it just dies.
I actually used to have the Display function as a class function and I moved it out because I thought that was the problem, but it wasn't.
Interestingly, if I change the declaration from 'Map test;' to 'Map* test = new Map;' and change the rest of the program appropriately, it works. Honestly though, doing that just seems kind of dumb, and I think that would slow everything down if I don't have a good reason to put everything on the heap. Plus, I don't like bandages. If there is a problem I'd rather fix it.
Any ideas?
You have a stack overflow (the condition, not the website).
The problem can be reproduced in this program:
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
Map test;
return 0;
}
It fails because it reaches stack limit.
Also tileMap[i][j].chr[2] is out of bound. It is declared as char chr[2]; valid index is 0 and 1. It can only go up to tileMap[i][j].chr[1]
Ditto b[], r[], and g[]
Change the Map class so that it allocates memory on heap and fix chr:
class Map
{
//Tile tileMap[256][256];
Tile **tileMap;
public:
Map();
~Map();
};
Map::Map()
{
int i, j;
tileMap = new Tile*[256];
for (i = 0; i < 256; i++)
tileMap[i] = new Tile[256];
for (i = 0; i<256; i++)
{
for (j = 0; j<256; j++)
{
//tileMap[i][j].chr[1] = 'X';
tileMap[i][j].chr[0] = 'X'; //<== meant to be 0?
tileMap[i][j].b[0] = 255;
tileMap[i][j].r[0] = 255;
tileMap[i][j].g[0] = 255;
//tileMap[i][j].chr[2] = ' ';
tileMap[i][j].chr[1] = ' '; //<== meant to be 1?
tileMap[i][j].b[1] = 0;
tileMap[i][j].r[1] = 0;
tileMap[i][j].g[1] = 0;
tileMap[i][j].solid = false;
tileMap[i][j].translucent = false;
tileMap[i][j].opacity = 255;
}
}
}
Map::~Map()
{
int i = 0;
for (i = 0; i < 256; i++)
delete[]tileMap[i];
delete[]tileMap;
}

C++ Pixels In Console Window

In C++ using Code::Blocks v10.05, how do I draw a single pixel on the console screen? Is this easy at all, or would it be easier to just draw a rectangle? How do I color it?
I'm sorry, but I just can't get any code from SOF, HF, or even cplusplus.com to work. This is for a Super Mario World figure on the screen. The game I think is 16-bit, and is for the SNES system. C::B says I need SDK for C::B. It says "afxwin.h" doesn't exist. Download maybe?
This is what I'm trying to make:
It depends on your OS. I suppose you are programming in a Windows platform, therefore you can use SetPixel but you have to use "windows.h" to get a console handle, so here an example for drawing the cos() function:
#include<windows.h>
#include<iostream>
#include <cmath>
using namespace std;
#define PI 3.14
int main()
{
//Get a console handle
HWND myconsole = GetConsoleWindow();
//Get a handle to device context
HDC mydc = GetDC(myconsole);
int pixel =0;
//Choose any color
COLORREF COLOR= RGB(255,255,255);
//Draw pixels
for(double i = 0; i < PI * 4; i += 0.05)
{
SetPixel(mydc,pixel,(int)(50+25*cos(i)),COLOR);
pixel+=1;
}
ReleaseDC(myconsole, mydc);
cin.ignore();
return 0;
}
You can also use some others libraries like: conio.h allegro.h sdl, etc.
If you're willing to have the image look blocky, you could take advantage of the block characters from the console code page.
█ = '\xDB' = U+2588 FULL BLOCK
▄ = '\xDC' = U+2584 LOWER HALF BLOCK
▀ = '\xDF' = U+2580 UPPER HALF BLOCK
and space
By using the half-blocks in combination with colored text, you can turn an 80×25 console window into an 80×50 16-color display. (This was the approach used by the QBasic version of Nibbles.)
Then, you just need to convert your image to the 16-color palette and a reasonably small size.
windows.h provides a function SetPixel() to print a pixel at specified location of a window. The general form of the function is
SetPixel(HDC hdc, int x, int y, COLORREF& color);
where, x and y are coordinates of pixel to be display and color is the color of pixel.
Important: to print the pixel in your machine with Code::blocks IDE, add a link library libgdi32.a (it is usually inside MinGW\lib ) in linker setting.
Console is a text device, so in general you don't write to individual pixels. You can create a special font and select it as a font for console, but it will be monochromatic. There are libraries which simplify writing console UI (e.g. Curses), but I believe that you also have more gamelike functionality in mind besides just showing a sprite.
if you want to write a game, I suggest taking a look at some of the graphics/game frameworks/libs, e.g. SDL
I have drawn the straight line using windows.h in code::blocks. I can't explain it in details, but I can provide you a code and procedure to compile it in code::blocks.
go to setting menu and select compiler and debugger.
Click on linker tab and add a link library libgdi32.a which is at C:\Program Files\CodeBlocks\MinGW\lib directory.
Now compile this program
#include <windows.h>
#include <cmath>
#define ROUND(a) ((int) (a + 0.5))
/* set window handle */
static HWND sHwnd;
static COLORREF redColor=RGB(255,0,0);
static COLORREF blueColor=RGB(0,0,255);
static COLORREF greenColor=RGB(0,255,0);
void SetWindowHandle(HWND hwnd){
sHwnd=hwnd;
}
/* SetPixel */
void setPixel(int x,int y,COLORREF& color=redColor){
if(sHwnd==NULL){
MessageBox(NULL,"sHwnd was not initialized !","Error",MB_OK|MB_ICONERROR);
exit(0);
}
HDC hdc=GetDC(sHwnd);
SetPixel(hdc,x,y,color);
ReleaseDC(sHwnd,hdc);
return;
// NEVERREACH //
}
void drawLineDDA(int xa, int ya, int xb, int yb){
int dx = xb - xa, dy = yb - ya, steps, k;
float xIncrement, yIncrement, x = xa, y = ya;
if(abs(dx) > abs(dy)) steps = abs(dx);
else steps = abs(dy);
xIncrement = dx / (float) steps;
yIncrement = dy / (float) steps;
setPixel(ROUND(x), ROUND(y));
for(int k = 0; k < steps; k++){
x += xIncrement;
y += yIncrement;
setPixel(x, y);
}
}
/* Window Procedure WndProc */
LRESULT CALLBACK WndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam){
switch(message){
case WM_PAINT:
SetWindowHandle(hwnd);
drawLineDDA(10, 20, 250, 300);
break;
case WM_CLOSE: // FAIL THROUGH to call DefWindowProc
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
default:
break; // FAIL to call DefWindowProc //
}
return DefWindowProc(hwnd,message,wParam,lParam);
}
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int iCmdShow){
static TCHAR szAppName[] = TEXT("Straight Line");
WNDCLASS wndclass;
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 = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
wndclass.lpszMenuName = NULL ;
wndclass.lpszClassName = szAppName ;
// Register the window //
if(!RegisterClass(&wndclass)){
MessageBox(NULL,"Registering the class failled","Error",MB_OK|MB_ICONERROR);
exit(0);
}
// CreateWindow //
HWND hwnd=CreateWindow(szAppName,"DDA - Programming Techniques",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL);
if(!hwnd){
MessageBox(NULL,"Window Creation Failed!","Error",MB_OK);
exit(0);
}
// ShowWindow and UpdateWindow //
ShowWindow(hwnd,iCmdShow);
UpdateWindow(hwnd);
// Message Loop //
MSG msg;
while(GetMessage(&msg,NULL,0,0)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
/* return no error to the operating system */
return 0;
}
In this program I have used DDA line drawing algorithm. Pixel drawing tasks is done by setPixel(ROUND(x), ROUND(y)) function.
This is windows programing which you can learn details here
To use in CodeBlocks I found this (you have to add a linker option -lgdi32):
//Code Blocks: Project Build Options Linker settings Othoer linker options: add -lgdi32
I forgot: You have to put this before including windows.h:
#define _WIN32_WINNT 0x0500
The whole cosine code again. Ready to compile:
//Code Blocks: Project Build Options Linker settings Othoer linker options: add -lgdi32
#define _WIN32_WINNT 0x0500
#include "windows.h"
#include <iostream>
#include <cmath>
using namespace std;
#define PI 3.14
int main(){
HWND myconsole = GetConsoleWindow();
HDC mydc = GetDC(myconsole);
int pixel =0;
COLORREF COLOR= RGB(255,255,255);
//Draw pixels
for(double i = 0; i < PI * 4; i += 0.05)
{
SetPixel(mydc,pixel,(int)(50+25*cos(i)),COLOR);
pixel+=1;
}
ReleaseDC(myconsole, mydc);
cin.ignore();
return 0;
}

Menu disappears after running program later

Okay, so at first when i run my win32 program the menu works fine, however when i open the application later the next day or such the menu is gone but the code never changed. im making the menu with a .rc file. is this the recommended way?
resource.rc
#include "resource.h"
IDR_MYMENU MENU
BEGIN
POPUP "&File"
BEGIN
MENUITEM "E&xit", ID_FILE_EXIT
END
END
resource.h
#define IDR_MYMENU 101
#define IDI_MYICON 201
#define ID_FILE_EXIT 9001
#define ID_STUFF_GO 9002
main.cpp
#include "resource.h"
wincl.lpszMenuName = MAKEINTRESOURCE(IDR_MYMENU);
also i noticed that MSVC++ has a very very complex windows templates, vs bloodshed. should i maybe give up on bloodshed and use MSVC++? I am use to blooshed, but i want to have an edge when i finally learn this stuff?
HWND hwnd; /* This is the handle for our window */
MSG messages; /* Here messages to the application are saved */
WNDCLASSEX wincl; /* Data structure for the windowclass */
/* The Window structure */
wincl.hInstance = hThisInstance;
wincl.lpszClassName = szClassName;
wincl.lpfnWndProc = WindowProcedure; /* This function is called by windows */
wincl.style = CS_DBLCLKS; /* Catch double-clicks */
wincl.cbSize = sizeof (WNDCLASSEX);
/* Use default icon and mouse-pointer */
wincl.hIcon = LoadIcon (GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON));
wincl.hIconSm = (HICON) LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON), IMAGE_ICON, 16, 16 ,0);
wincl.hCursor = LoadCursor (NULL, IDC_CROSS);
wincl.lpszMenuName = MAKEINTRESOURCE(IDR_MYMENU); /* No menu */
wincl.cbClsExtra = 0; /* No extra bytes after the window class */
wincl.cbWndExtra = 0; /* structure or the window instance */
/* Use Windows's default color as the background of the window */
wincl.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
/* Register the window class, and if it fails quit the program */
if (!RegisterClassEx (&wincl))
return 0;
/* The class is registered, let's create the program*/
hwnd = CreateWindowEx (
0, /* Extended possibilites for variation */
szClassName, /* Classname */
"Windows App", /* Title Text */
WS_OVERLAPPEDWINDOW, /* default window */
CW_USEDEFAULT, /* Windows decides the position */
CW_USEDEFAULT, /* where the window ends up on the screen */
544, /* The programs width */
375, /* and height in pixels */
HWND_DESKTOP, /* The window is a child-window to desktop */
NULL, /* No menu */
hThisInstance, /* Program Instance handler */
NULL /* No Window Creation data */
);
The content of your RC file looks fine, so I don't think the problem is there. I doubt the problem is in Bloodshed either -- while I'm not particularly fond of Dev-C++, I doubt it's causing anything like this. That leaves your code for the application as the most likely culprit for causing the problem. Unfortunately, you haven't shown enough of that to even guess at likely sources of the problem.

Image wont draw to screen C++

I am following a tutorial. And I am trying to draw a .bmp file to the screen. It builds with no errors but no image appears. according to the book, I should see the image pop up in random places. Below is my code. The author doesnt recommend this technique for drawing objects, he is just doing for demostration. In case your wondering.
The image is a 25x25 square red square.
#include <windows.h>
#include <iostream>
#include <time.h>
using namespace std;
const string APPTITLE = "Game Loop";
HWND window;
HDC device;
bool gameover = false;
void DrawBitmap(char *filename, int x, int y)
{
//load the bitmap image
HBITMAP image = (HBITMAP)LoadImage(0,"c.bmp", IMAGE_BITMAP,0,0, LR_LOADFROMFILE);
BITMAP bm;
GetObject(image, sizeof(BITMAP), &bm);
HDC hdcImage = CreateCompatibleDC(device);
SelectObject(hdcImage,image);
BitBlt(
device,
x,y,
bm.bmWidth, bm.bmHeight,
hdcImage,
0,0,
SRCCOPY);
//deletec the device context and bitmap
DeleteDC(hdcImage);
DeleteObject((HBITMAP)image);
}
bool Game_Init()
{
srand(time(NULL));
return 1;
}
void Game_Run()
{
if(gameover == true) return;
RECT rect;
GetClientRect(window, &rect);
//draw bitmap at random location
int x = rand() % (rect.right - rect.left);
int y = rand() % (rect.bottom - rect.top);
DrawBitmap("c.bmp",x,y);
}
void Game_End()
{
//free the device
ReleaseDC(window,device);
}
LRESULT CALLBACK WinProc(HWND hWnd, UINT message, WPARAM WParam, LPARAM lparam)
{
switch(message)
{
case WM_DESTROY:
gameover = true;
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, message, WParam, lparam);
}
ATOM MyRegisterClass(HINSTANCE hInstance)
{
//set the new windows properties
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC) WinProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName= APPTITLE.c_str();
wc.hIconSm = NULL;
return RegisterClassEx(&wc);
}
bool InitInstance(HINSTANCE hInstance, int nCmdShow)
{
//create a new window
window = CreateWindow(
APPTITLE.c_str(),
APPTITLE.c_str(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
640,480,
NULL,
NULL,
hInstance,
NULL);
//was there an error creating the window ?
if(window == 0) return 0;
//display the window
ShowWindow(window, nCmdShow);
UpdateWindow(window);
device = GetDC(window);
return 1;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
//declare variables
MSG msg;
//register the class
MyRegisterClass(hInstance);
//initialize application
if(!InitInstance(hInstance, nCmdShow)) return 0;
//initilize the game
if(!Game_Init()) return 0;
//main message loop
while(!gameover)
{
if(PeekMessage(&msg,NULL, 0, 0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Game_Run();
}
Game_End();
return msg.wParam;
}
I am not sure if its because I have the image in the wrong location. but if that was the case. I figure it would throw a error. I have the image placed at the root of my source folder.
[EDIT]
Also , when I rebuild, I get a warning which might be a cause but here is the warning
1>------ Rebuild All started: Project: Begin, Configuration: Debug Win32 ------
1>Deleting intermediate and output files for project 'Begin', configuration 'Debug|Win32'
1>Compiling...
1>main.cpp
1>c:\users\numerical25\documents\visual studio 2008\projects\begin\begin\main.cpp(39) : warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data
1>Compiling manifest to resources...
1>Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1
1>Copyright (C) Microsoft Corporation. All rights reserved.
1>Linking...
1>LINK : C:\Users\numerical25\Documents\Visual Studio 2008\Projects\Begin\Debug\Begin.exe not found or not built by the last incremental link; performing full link
1>Embedding manifest...
1>Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1
1>Copyright (C) Microsoft Corporation. All rights reserved.
1>Build log was saved at "file://c:\Users\numerical25\Documents\Visual Studio 2008\Projects\Begin\Begin\Debug\BuildLog.htm"
1>Begin - 0 error(s), 1 warning(s)
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========
The code does work, you just forgot to put your c.bmp in the right location. Put it in the project output folder (i.e. bin/Debug) if you're launching the program from Explorer or to the project folder if you're lanching the program from Visual Studio.
Your code seems to work, for a sufficiently loose definition of "work". Unless you've modified the code (quite a bit) in attempting to make it work, my advice would be to find a different tutorial to follow -- at least to me, most of what's there right now is quite unimpressive.
Just for example, Game_Run() passes the name of the bitmap file as a parameter to Draw_Bitmap(), but the parameter gets ignored, and Draw_Bitmap() uses a hard-coded file name instead.
The PeekMessage() loop makes the program look like it was written about 25 years ago, in the days of 16-bit Windows (and arguably not so great even then). There's rarely (if ever) a good reason to use PeekMessage() in a new code, and code that did use it is probably overdue for an overhaul. The main loop normally uses GetMessage(), and you can (for example) use SetTimer (with a duration of 0) to compute new coordinates for drawing the bitmap, and then calling InvalidateRect() to get it drawn. At one time there was a fair argument that the extra messages involved in this caused excessive overhead, but on a modern machine it'll keep up with the monitor refresh rate while using on the order of 10% of the CPU or less.
To keep CPU usage down, however, you want to restructure the code a bit -- right now, every time you draw, you're getting the window rectangle, reloading the BMP from disk, selecting the BMP into a compatible DC, and finally BitBlting to get the image to the screen. That's the part of the code where optimization will make a difference -- by strong preference, you want it to just call BitBlt and be done. The rest of the code should be moved elsewhere so it happens only when needed. For example, you can retrieve the window rectangle in response to WM_SIZE, and just save it in-between. Since you're using the same bitmap for the duration, load it once, and from them on just display it.