SetWindowPos() sometimes does not resize child-windows - c++

First, I use Createprocess() to open all desired windows. (Not Listed)
After the successful opening of the processes I find with the FindWindow () and FindWindowEx() all available windows. (Listed)
Sometimes the function SetWindowPos() does not work properly. A few windows were sorted out a few not. But this case does not always occur!
For improvements I always have an open ear!
//Some Variables comming from other code : numberOfWindows / numberOfStartedWindows
//Variables
bool trigger = true;
bool targetProcess = true;
HWND hwnd, hwndChilds = NULL;
int targetsFound = 0;
int targetsFoundMath = 0;
bool searchWindows = true;
//Start targetProcess
while (targetProcess) {
//If targetsFround == numberOfWindows then exit targetProcess.
if (targetsFound == numberOfWindows)
{
targetProcess = false;
}
//If all Windows are Started then start search loop
if (numberOfStartedWindows == numberOfWindows)
{
trigger = false;
}
//We starting search loop...
if (!trigger && targetProcess) {
//Find the Main Window.
hwnd = FindWindow(0, _T("World of Warcraft"));
if (hwnd)
{
targetsFound += 1;
//Set Window Foreground and call SetWindowPos to change Position
if (SetForegroundWindow(hwnd)) {
if (!SetWindowPos(hwnd, HWND_TOP, 0, 0, 1920, 800, SWP_SHOWWINDOW))
{
cout << "Error: HWND Failed with SETWINDOWPOS" << endl;
}
}
//Store HWND in StoreWindows
StoreWindows.emplace_back(hwnd);
//Now we search for child Windows
while (searchWindows)
{
//do it if targetsFound not numberOfWindows
if (targetsFound != numberOfWindows)
{
//Get Child Window
hwndChilds = FindWindowEx(NULL, hwnd, NULL, _T("World of Warcraft"));
if (hwndChilds != NULL)
{
//Little Math for Position
targetsFoundMath = (targetsFound - 1) * 384;
//if window in foreground SetWindowPos.
if(SetForegroundWindow(hwndChilds)){
if (!SetWindowPos(hwndChilds, HWND_TOP, targetsFoundMath, 800, 384, 280, SWP_SHOWWINDOW))
{
cout << "Error: HWNDChilds Failed with SETWINDOWPOS" << endl;
}
}
/*targetsFound += 1;
StoreWindows.emplace_back(hwndChilds);*/
//If all targetsFound then quit this loop after finish
if (targetsFound == numberOfWindows) {
searchWindows = false;
cout << "false" << targetsFound << endl;
}
//StoreChild Window and Add targetsfround +1
targetsFound += 1;
StoreWindows.emplace_back(hwndChilds);
}
else {
searchWindows = false;
cout << "no more child objects found!" << endl;
}
}
else
{
searchWindows = false;
}
}
}
}
}
cout << "Window Size: " << StoreWindows.size() << endl;
Funny when I debugs:
RECT debugRect;
for (int x = 0; x < StoreWindows.size(); x++)
{
GetClientRect(StoreWindows[x], &debugRect);
cout << debugRect.left << " " << debugRect.right<< " " << debugRect.bottom<< " " << debugRect.top << endl;
//debugRect.right = breite vom fenster // debugRect.bottom = Höhe
}
The output from the Position looks good but the Window isnt on the right place :/
Debug:
Im out of ideas and hope you can help me! If you need more explanations, do not hesitate to ask.
With problems it looks so..
If everything goes without problems it looks like this:

The problem was the duplicate (same) window partial to be found. Because the start process takes longer than the Find Func. Now i have Fixxed the loop. (Its wait now for all success windows.)
bool mainWindow = false;
bool searchHwndStrike = false;
int targetResult = 0;
while (true)
{
//Search first Window
if (!mainWindow) {
hwnd = FindWindow(0, _T("World of Warcraft"));
if (hwnd != NULL)
{
if (SetForegroundWindow(hwnd)) {
if (!SetWindowPos(hwnd, HWND_TOP, 0, 0, 1920, 800, SWP_SHOWWINDOW))
{
cout << "Error: HWND Failed with SETWINDOWPOS" << endl;
}
}
cout << "Main window found." << endl;
mainWindow = true;
StoreWindows.emplace_back(hwnd);
}
}else {
if (StoreWindows.size() < numberOfWindows) {
hwnd = FindWindowEx(NULL, hwnd, NULL, _T("World of Warcraft"));
if (hwnd != NULL)
{
for (int x = 0; x < StoreWindows.size(); x++)
{
if (StoreWindows[x] == hwnd)
{
searchHwndStrike = true;
}
}
if (!searchHwndStrike)
{
cout << "Child window found." << endl;
cout << targetResult << endl;
targetResult = (StoreWindows.size()-1) * 384;
//if window in foreground SetWindowPos.
if (SetForegroundWindow(hwnd)) {
if (!SetWindowPos(hwnd, HWND_TOP, targetResult, 800, 384, 280, SWP_SHOWWINDOW))
{
cout << "Error: HWNDChilds Failed with SETWINDOWPOS" << endl;
}
}
StoreWindows.emplace_back(hwnd);
}
searchHwndStrike = false;
}
}
else {
break;
}
}
}
cout << StoreWindows.size() << endl;

Related

WriteProcessMemory not working for some reason

This is all the source code for a program i'm trying to make, and I can't get WriteProcessMemory to work at all. It returns the correct messages, saying that everything went successfully, but nothing actually changes in the game. Does anyone know of a fix?
#include <iostream>
#include <Windows.h>
using namespace std;
// variables
int plcHold = 1;
string hlthLoop = "OFF";
string ammoLoop = "OFF";
DWORD pid;
DWORD playerAddr;
DWORD hlthOffs = 0xF8;
// main function
int main()
{
// finding pid, opening proc, finding player address
HWND hwnd = FindWindowA(NULL, "AssaultCube");
if(hwnd == NULL)
{
cout << "Error; Couldn't find window" << endl;
} else{
GetWindowThreadProcessId(hwnd, &pid);
HANDLE pHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if(pHandle == NULL)
{
cout << "Error; Couldn't open process" << endl;
} else{
ReadProcessMemory(pHandle, (LPCVOID)0x50F4F4, &playerAddr, sizeof(playerAddr), 0);
if(ReadProcessMemory != FALSE)
{
cout << "Health successfully read!" << endl;
} else{
cout << "Error code " << GetLastError << endl;
}
}
while(plcHold == 1){
cout << "========== *****'s Assault Cube Trainer ==========\n" << endl;
cout << "=============== Health Loop - " << hlthLoop << " ================" << endl;
Sleep(1500);
system("cls");
if(GetAsyncKeyState(0x5A))
{
cout << "Health successfully edited!" << endl;
WriteProcessMemory(pHandle, LPVOID(playerAddr + hlthOffs), 0, sizeof(999), 0);
CloseHandle(pHandle);
}
}
}
return 0;
}
You're passing a null pointer to WriteProcessMemory for the third (lpBuffer) parameter. You have to pass the address of the actual value, not the value itself. If you want to write an integer value, try this:
DWORD val = 0; // or 999?
WriteProcessMemory(
pHandle, static_cast<LPVOID>(playerAddr + hlthOffs),
&val, sizeof(val), 0);

getrawinputdata within a simple main()

I am trying to read values from the joystick using simple C++ techniques and Windows.
My aim is to write a program that sends a keyboard command whenever the joystick signal exceeds a predefined threshold. The keyboard command will be picked up by whichever window would be active at the time.
My C++ coding skills are limited so I wish to do this in the simplest way, preferably within one main().
Up to now I have managed to register the joystick.
But I stumbled across the first problem, which is how to use GetRawInputData(). I found a lot of examples about this within a win32 structure, but am struggling to translate this to a simple main().
My code till now is the following:
#include <windows.h>
#include <iostream>
RAWINPUTDEVICE Rid[1];
int main()
{
UINT bufferSize;
Rid[0].usUsagePage = 0x01;
Rid[0].usUsage = 0x05;
Rid[0].dwFlags = 0;
Rid[0].hwndTarget = 0;
if (RegisterRawInputDevices(Rid, 1, sizeof(Rid[0])) == FALSE)
{
std::cout << "Registration failed" << std::endl;
return 1;
}
else
{
std::cout << "Registration OK" << std::endl;
while (1)
{
// This is the part in which I would like to read the joystick values
// and determine whether to send a keyboard event or not.
}
}
return 0;
}
Can you help?
Thanks.
UPDATE
Following the suggestion to use joyGetInput(), here is the updated code:
#include<Windows.h>
#include<iostream>
#include<time.h>
using namespace std;
#define mid 32767
#define trig 1804
#define reset 1475
int main()
{
JOYINFO pos;
UINT result;
SYSTEMTIME st;
INPUT xi, yi, zi;
int i = 0;
int state[6] = { 0,0,0,0,0,0 };
int uu = mid + trig;
int ul = mid + reset;
xi.type = INPUT_KEYBOARD;
yi.type = INPUT_KEYBOARD;
zi.type = INPUT_KEYBOARD;
while (1)
{
result = joyGetPos(i, &pos);
if (result != JOYERR_NOERROR)
{
cout << "JoyID " << i << " returned an error. Trying the next one." << endl;
i++;
if (i > 15)
{
cout << "Reached the maximum allowed attempts. Exiting." << endl;
return 1;
}
}
else
{
//GetSystemTime(&st);
//cout << st.wHour << ":" << st.wMinute << ":" << st.wSecond << ":" << st.wMilliseconds << "\tX: " << pos.wXpos << "\tY: " << pos.wYpos << "\tZ: " << pos.wZpos << endl;
if (pos.wXpos > uu && state[0] == 0)
{
xi.ki.wVk = 0x30;
xi.ki.dwFlags = 0;
SendInput(1, &xi, sizeof(INPUT));
state[0] = 1;
GetSystemTime(&st);
cout << "Key down - X axis" << endl;
cout << st.wHour << ":" << st.wMinute << ":" << st.wSecond << ":" << st.wMilliseconds << "\tX: " << pos.wXpos << "\tY: " << pos.wYpos << "\tZ: " << pos.wZpos << endl;
}
if (pos.wXpos < ul && state[0] == 1)
{
xi.ki.wVk = 0x30;
xi.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &xi, sizeof(INPUT));
state[0] = 0;
GetSystemTime(&st);
cout << "Key up - X axis" << endl;
cout << st.wHour << ":" << st.wMinute << ":" << st.wSecond << ":" << st.wMilliseconds << "\tX: " << pos.wXpos << "\tY: " << pos.wYpos << "\tZ: " << pos.wZpos << endl;
}
}
}
return 0;
}
My new question now is:
How do you simulate a long key press? I would like the target window to behave just like a user kept pressing on the key. With the above code, the key is issued only once.
GetRawInputData() takes an HRAWINPUT handle as input. The only place you can get that handle is from the LPARAM parameter of the WM_INPUT window message.
Your main() function needs to use CreateWindow/Ex() to create a window (if you don't want the user to see it, consider making a message-only window), specify that window in the joystick's RAWINPUTDEVICE::hwndTarget field when you call RegisterRawInputDevices(), and then run a message loop so the window can receive messages. For example:
#include <windows.h>
#include <iostream>
int main()
{
WNDCLASSEX wx = {};
wx.cbSize = sizeof(WNDCLASSEX);
wx.lpfnWndProc = DefWindowProc;
wx.hInstance = GetModuleHandle(NULL);
wx.lpszClassName = TEXT("MyRawInputWndClass");
if (!RegisterClassEx(&wx))
{
std::cout << "Window Class Registration failed" << std::endl;
return 1;
}
HWND hWnd = CreateWindowEx(0, wx.lpszClassName, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, wx.hInstance, NULL);
if (!hWnd)
{
std::cout << "Window Creation failed" << std::endl;
return 1;
}
RAWINPUTDEVICE Rid = {};
Rid.usUsagePage = 0x01;
Rid.usUsage = 0x05;
Rid.dwFlags = 0;
Rid.hwndTarget = hWnd;
if (!RegisterRawInputDevices(&Rid, 1, sizeof(RAWINPUTDEVICE)))
{
std::cout << "Device Registration failed" << std::endl;
return 1;
}
std::cout << "Device Registration OK" << std::endl;
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
if (msg.message == WM_INPUT)
{
HRAWINPUT hRawInput = reinterpret_cast<HRAWINPUT>(msg.lParam);
// retrieve and process data from hRawInput as needed...
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
Alternatively:
#include <windows.h>
#include <iostream>
LRESULT CALLBACK MyWndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
if (Msg == WM_INPUT)
{
HRAWINPUT hRawInput = reinterpret_cast<HRAWINPUT>(lParam);
// retrieve and process data from hRawInput as needed...
}
return DefWindowProc(hWnd, Msg, wParam, lParam);
}
int main()
{
WNDCLASSEX wx = {};
wx.cbSize = sizeof(WNDCLASSEX);
wx.lpfnWndProc = &MyWndProc;
wx.hInstance = GetModuleHandle(NULL);
wx.lpszClassName = TEXT("MyRawInputWndClass");
if (!RegisterClassEx(&wx))
{
std::cout << "Window Class Registration failed" << std::endl;
return 1;
}
HWND hWnd = CreateWindowEx(0, wx.lpszClassName, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, wx.hInstance, NULL);
if (!hWnd)
{
std::cout << "Window Creation failed" << std::endl;
return 1;
}
RAWINPUTDEVICE Rid = {};
Rid.usUsagePage = 0x01;
Rid.usUsage = 0x05;
Rid.dwFlags = 0;
Rid.hwndTarget = hWnd;
if (!RegisterRawInputDevices(&Rid, 1, sizeof(RAWINPUTDEVICE)))
{
std::cout << "Device Registration failed" << std::endl;
return 1;
}
std::cout << "Device Registration OK" << std::endl;
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
I suggest you read the Raw Input documentation more carefully. This is all explained in detail. If you don't specify a window to RegisterRawInputDevices(), the OS will send the WM_INPUT messages to whichever window currently has the keyboard focus, which is not what you want.
That being said, if you want something simplier, you might consider using joyGetPosEx() instead of Raw Input.

TTF_RenderText_Solid() Crashing Game and Visual Studio [c++][sdl ttf]

Stack Trace :
So, I'm trying to create a 2D game and right now I'm trying to display and move a image, however when I Debug the game/run it, visual studio and the game freezes and can't quit, not even when using the task manager to kill it.
The only way to unfreeze it is by logging off or restarting the pc which forces both of them to close.
I also get some weird error :
Unhandled exception at 0x71002A95 (SDL2_ttf.dll) in SDLGame.exe: 0xC0000005: Access violation reading location 0x00000000.
I have no idea what it means and how to fix it, but I'm guessing it has something to do with my code that I need to change.
Here's my code :
#include <iostream>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
// Macros
#define pause system("PAUSE"); // Works on windows only, removed in alpha / beta versions.
// Pre "init" of functions
void QuitGame();
int InitGame();
void processInput();
void InitRects();
// Variables
int FramesPassed = 0;
int FramesPerSecond = 0; // Not used yet
SDL_Renderer* renderer = nullptr;
SDL_Window* window = nullptr;
SDL_Event evnt;
SDL_Rect sprite1_Rect;
SDL_Rect FPS_Text_Rect;
TTF_Font* Sans = TTF_OpenFont("Fonts/Aaargh.ttf", 40);
SDL_Color Color_White = { 255, 255, 255 };
SDL_Surface* FPS_Text_Surface = nullptr;
SDL_Texture* FPS_Text = nullptr;
SDL_Texture* testImg = nullptr;
static bool isRunning = true;
int SDL_main(int argc, char* argv[])
{
InitGame();
InitRects();
std::cout << "Displaying text on screen using SDL TTF doesn't work" << std::endl;
std::cout << "This happens when the TTF Surface is being rendered on screen" << std::endl;
std::cout << "check line : 123 and 124." << std::endl;
while (isRunning)
{
FramesPassed++;
processInput();
SDL_RenderClear(renderer); // Clears the last/current frame?
// Render testImage on screen. (needs to be between render present and clear.)
SDL_RenderCopy(renderer, testImg, NULL, &sprite1_Rect);
SDL_RenderCopy(renderer, FPS_Text, NULL, &FPS_Text_Rect);
SDL_RenderPresent(renderer); // Pretty much draws everything again.
}
return 0;
QuitGame();
}
int InitGame()
{
std::cout << "Game Initializing..." << std::endl;
std::cout << "TTF SDL Initializing..." << std::endl;
if (TTF_Init() < 0)
{
std::cout << "SDL TTF Failed To Initialize : " << TTF_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "SDL TTF Initialized Successfully" << std::endl;
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
std::cout << "SDL Initialization Failed : " << SDL_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "SDL Initializing" << std::endl;
window = SDL_CreateWindow("Game Title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 720, SDL_WINDOW_SHOWN);
if (window == NULL)
{
std::cout << "Window Creation Failed : " << SDL_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "SDL Initialized Successfully" << std::endl;
std::cout << "Renderer Initializing..." << std::endl;
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL)
{
std::cout << "Renderer Creation Failed : " << SDL_GetError() << std::endl;
pause
QuitGame();
}
else
{
std::cout << "Renderer Initialized Successfully" << std::endl;
// This line (under) crashes game, and crashes visual studio...
FPS_Text_Surface = TTF_RenderText_Solid(Sans, "Frames Passed : " + FramesPassed, Color_White);
testImg = IMG_LoadTexture(renderer, "images/test.bmp");
FPS_Text = SDL_CreateTextureFromSurface(renderer, FPS_Text_Surface);
}
}
}
}
std::cout << "Game Has Successfully Initialized!" << std::endl;
return 0;
}
void InitRects()
{
sprite1_Rect.h = 32;
sprite1_Rect.w = 32;
sprite1_Rect.x = 10;
sprite1_Rect.y = 10;
FPS_Text_Rect.h = 100;
FPS_Text_Rect.w = 50;
FPS_Text_Rect.x = 2;
FPS_Text_Rect.y = 2;
}
void processInput()
{
if (SDL_PollEvent(&evnt)) {
switch (evnt.type) {
case SDL_QUIT:
QuitGame();
break;
case SDL_KEYDOWN:
switch (evnt.key.keysym.sym) {
case SDLK_a:
sprite1_Rect.x -= 1;
break;
case SDLK_d:
sprite1_Rect.x += 1;
break;
case SDLK_w:
sprite1_Rect.y-= 1;
break;
case SDLK_s:
sprite1_Rect.y += 1;
break;
}
break;
}
}
}
void QuitGame()
{
isRunning = false;
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
The problem is that you have the font as a global variable and load it straight away!
You need to call TTF_Init() first and load the font after!
By using a global vairable your loading it before initializing SDL_TTF, and this way TTF_OpenFont() will return a nullptr and if you try to read a nullptr gives an Access violation reading location 0x00000000 error!
Just call TTF_OpenFont() in a function and after TTF_Init() and it will work!
Just a tip you should check that Sans isn't a nullptr before using it!

Code::Blocks executable file doesn't have textures

I've made a basic program using the SFML library in Code::Blocks, and now all I want to do is send it to a friend. I've built my program in both debug and release mode, yet whenever I run the .exe file from my bin, it simply will not load the textures. Of course when I run it within the Code::Blocks client, it works perfectly. I'm not sure if I need to package my work or send the files separately or what, but any help would be much appreciated
Here's the code in case it's helpful somehow (I know it's not pretty):
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <string>
#include <iostream>
#include <Windows.h>
int main(){
sf::RenderWindow Window;
Window.create(sf::VideoMode(800, 600), "Enjoy :)");
sf::Clock clock;
int pixelFindX = 0, pixelFindY = 0;
int oldLoc = 0, newLoc = 0;
int changeVal = 1;
int tripleCheck = 0;
int xLoc = 0, yLoc = 100;
double timeChecker = 0;
bool execute = false, secondExecute = false;
bool oldSide = false, newSide = false, changer = true;
bool drawLeft = false, drawRight = false, drawCenter = false;
sf::Texture pTexture;
sf::Sprite playerImage;
if(!pTexture.loadFromFile("Pixel Dude.png")){
std::cout << "Could not load pTexture file" << std::endl;
}
sf::Texture bTexture;
sf:: Sprite backgroundImage;
if(!bTexture.loadFromFile("molester moon background IS DONE.jpg")){
std::cout << "Could not load bTexture file" << std::endl;
}
sf::Texture bridgeTexture;
sf::Sprite bridgeImageL;
sf::Sprite bridgeImageR;
if(!bridgeTexture.loadFromFile("pixel bridge.jpg")){
std::cout << "Could not load bridgeTexture file" << std::endl;
}
sf::Texture trophyTexture;
sf::Sprite trophyImage;
if(trophyTexture.loadFromFile("trophy pixeled.png")){
std::cout << "Could not load trophyTexture file" << std::endl;
}
sf::String stringL = "Move to the Left!", stringR = "Move to the Right!", stringC = "You are currently balanced.";
sf::String stringGo = stringL;
sf::Font font;
if(!font.loadFromFile("arial.ttf")){
std::cout << "Could not load font file" << std::endl;
}
sf::Text text(stringGo, font, 50);
text.setPosition(xLoc, yLoc);
text.setStyle(sf::Text::Bold);
playerImage.setTexture(pTexture);
playerImage.setPosition(336, 355);
playerImage.setScale(4,4);
playerImage.setTextureRect(sf::IntRect(pixelFindX*32, pixelFindY*32, 32, 32));
backgroundImage.setTexture(bTexture);
backgroundImage.setPosition(0,0);
bridgeImageL.setTexture(bridgeTexture);
bridgeImageL.setPosition(0, 450);
bridgeImageL.setScale(4.17,4.68);
bridgeImageR.setTexture(bridgeTexture);
bridgeImageR.setPosition(400,450);
bridgeImageR.setScale(4.17, 4.68);
trophyImage.setTexture(trophyTexture);
trophyImage.setPosition(600, 305);
trophyImage.setScale(2,2);
sf::View view;
sf::View viewReg;
view.reset(sf::FloatRect(0, 0, 800, 600));
view.setViewport(sf::FloatRect(0, 0, 1, 1));
viewReg.reset(sf::FloatRect(0, 0, 800, 600));
viewReg.setViewport(sf::FloatRect(0, 0, 1, 1));
std::cout << "Player Dimensioms: Width = " << playerImage.getGlobalBounds().width << ", Height = " << playerImage.getGlobalBounds().height << std::endl;
while(Window.isOpen()){
clock.restart();
sf::Event Event;
while(Window.pollEvent(Event)){
switch(Event.type){
case sf::Event::Closed:
Window.close();
break;
case sf::Event::KeyPressed:
if(Event.key.code == sf::Keyboard::Escape){
Window.close();
}
break;
}
}
//std::cout << timeChecker << std::endl;
timeChecker += clock.getElapsedTime().asSeconds();
if(timeChecker >= .00025){
execute = true;
timeChecker = 0;
//std::cout << "execute = true" << std::endl;
}
oldLoc = playerImage.getPosition().x;
oldSide = changer;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::D) && execute){
playerImage.move(1, 0);
pixelFindY = 2;
tripleCheck++;
changer = true;
//std::cout << "d called" << std::endl;
} else if(sf::Keyboard::isKeyPressed(sf::Keyboard::A) && execute){
playerImage.move(-1, 0);
pixelFindY = 1;
tripleCheck++;
changer = false;
//std::cout << "a called" << std::endl;
}
if(playerImage.getPosition().x < -96){
playerImage.setPosition(800, playerImage.getPosition().y);
} else if(playerImage.getPosition().x > 800){
playerImage.setPosition(-96, playerImage.getPosition().y);
}
newLoc = playerImage.getPosition().x;
newSide = changer;
pixelFindX += changeVal;
if(pixelFindX > 2){
pixelFindX -= 2;
changeVal = -1;
} else if(pixelFindX < 0){
pixelFindX += 2;
changeVal = 1;
}
if(oldLoc != newLoc && tripleCheck > 40 || oldSide != newSide){
playerImage.setTextureRect(sf::IntRect(pixelFindX*32, pixelFindY*32, 32, 32));
tripleCheck = 0;
//std::cout << "Yes called, pixelFindX = " << pixelFindX << ", tripleCheck = " << tripleCheck << std::endl;
} else {
//std::cout << "-----Not called, pixelFindX = " << pixelFindX << ", tripleCheck = " << tripleCheck << std::endl;
}
execute = false;
/* if(playerImage.getPosition().x + 128 > trophyImage.getPosition().x && playerImage.getPosition().x < trophyImage.getPosition().x + 192){
view.rotate(.0001);
}
*/
if(playerImage.getPosition().x > 500 - 128){
view.rotate(-.01);
drawRight = true;
} else if (playerImage.getPosition().x < 300 - 128){
view.rotate(.01);
drawLeft = true;
} else{
drawCenter = true;
}
//std::cout << "Player X: " << playerImage.getPosition().x + 128 << ", Trophy X: " << trophyImage.getPosition().x << std::endl;
if(drawLeft){
stringGo = stringR;
xLoc = 0;
} else if (drawRight){
stringGo = stringL;
xLoc = 800 - text.getGlobalBounds().width - 10;
} else if(drawCenter){
stringGo = stringC;
xLoc = 400 - text.getGlobalBounds().width / 2;
}
text.setPosition(xLoc, yLoc);
text.setString(stringGo);
Window.setView(viewReg);
Window.draw(backgroundImage);
Window.draw(text);
Window.setView(view);
Window.draw(bridgeImageL);
Window.draw(bridgeImageR);
// Window.draw(trophyImage);
Window.draw(playerImage);
Window.display();
Window.clear();
drawLeft = false;
drawRight = false;
drawCenter = false;
//Sleep(50);
}
}
Copy the compiled executable into a new folder and paste there the textures too. This folder you can send your friend (e.g. in a rar-archive).The textures won't load because probably the textures weren't in the bin/debug or bin/release folder. There are in another place wich is in the debugging mode is set as the working directory.If you want to change that (what I would not recommend) you can go to Project -> Properties -> Build targets -> [name of target] -> Execution working dir and change it to the directory where the compiled executables went.

creating clickable "buttons" c++

hey i am trying to basically just make a button in my little console application which can be pressed. here's a snippet of what i use to get the cursor location
if (GetKeyState(VK_LBUTTON) < 0) {
{
POINT p;
if (GetCursorPos(&p))
{
cout<<"\nSCREEN\nx coord->";
cout<<p.x;
cout<<"\ny coord->";
cout<<p.y;
}
SetConsoleTitle("paint");
HWND hWnd;
hWnd = FindWindow(NULL, "paint");
if (ScreenToClient(hWnd, &p));
{
cout<<"\n\nWINDOW\nx coord->";
cout<<p.x;
cout<<"\ny coord->";
cout<<p.y;
}
int pwx;
int pwy;
pwx=p.x;
pwy=p.y;
this just prints the mouse coords relative to the screen and to the window to the console. i got a function in which i can draw the ascii-symbol 219 to basically "paint" in the console wherever the mouse is and whenever the left mousebutton is held down.
now:
how can i detect a click within console characters?
cout<<"press here to clear the screen->[x]";
the 2 square brackets and the 'x' should be pressable.
i can only search for pixels with the above code, but not for rows and columns..
is there a way to do this or am i completely off the track?
i'm using code::blocks
thanks for your help!
[ i just started programming like a week ago so be nice :) ]
Here is some console mouse handling code to study. It does somewhat what you wrote you needed, It works on Visual studio but i hope it is runnable on code::blocks too.
More info can be found here :https://msdn.microsoft.com/en-us/library/windows/desktop/ms685035(v=vs.85).aspx
#include <iostream>
#include <stdio.h>
#include <windows.h>
HANDLE hStdin;
DWORD fdwSaveOldMode;
void ErrorExit(LPSTR);
void KeyEventProc(KEY_EVENT_RECORD);
void MouseEventProc(MOUSE_EVENT_RECORD);
void ResizeEventProc(WINDOW_BUFFER_SIZE_RECORD);
void GetMousePosWin(MOUSE_EVENT_RECORD);
void gotoXY(int x, int y);
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
COORD CursorPosition;
int main()
{
DWORD cNumRead, fdwMode, i;
INPUT_RECORD irInBuf[128];
int counter=0;
// Get the standard input handle.
hStdin = GetStdHandle(STD_INPUT_HANDLE);
if (hStdin == INVALID_HANDLE_VALUE)
ErrorExit("GetStdHandle");
// Save the current input mode, to be restored on exit.
if (! GetConsoleMode(hStdin, &fdwSaveOldMode) )
ErrorExit("GetConsoleMode");
// Enable the window and mouse input events.
fdwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
if (! SetConsoleMode(hStdin, fdwMode) )
ErrorExit("SetConsoleMode");
// Loop to read and handle the next 100 input events.
gotoXY(33,10);
std::cout << "\xDB Menu Item 1";
gotoXY(33,12);
std::cout << "\xDB Menu Item 2";
gotoXY(33,14);
std::cout << "\xDB Menu Item 3";
gotoXY(33,16);
std::cout << "\xDB Quit";
while (!counter)//++ <= 200)
{
// Wait for the events.
if (! ReadConsoleInput(
hStdin, // input buffer handle
irInBuf, // buffer to read into
128, // size of read buffer
&cNumRead) ) // number of records read
ErrorExit("ReadConsoleInput");
// Dispatch the events to the appropriate handler.
for (i = 0; i < cNumRead; i++)
{
switch(irInBuf[i].EventType)
{
case KEY_EVENT: // keyboard input
KeyEventProc(irInBuf[i].Event.KeyEvent);
break;
case MOUSE_EVENT: // mouse input
MouseEventProc(irInBuf[i].Event.MouseEvent);
gotoXY(33,8);
GetMousePosWin(irInBuf[i].Event.MouseEvent);
break;
case WINDOW_BUFFER_SIZE_EVENT: // scrn buf. resizing
ResizeEventProc( irInBuf[i].Event.WindowBufferSizeEvent );
break;
case FOCUS_EVENT: // disregard focus events
case MENU_EVENT: // disregard menu events
break;
default:
ErrorExit("Unknown event type");
break;
}
}
}
// Restore input mode on exit.
SetConsoleMode(hStdin, fdwSaveOldMode);
return 0;
}
VOID ErrorExit (LPSTR lpszMessage)
{
fprintf(stderr, "%s\n", lpszMessage);
// Restore input mode on exit.
SetConsoleMode(hStdin, fdwSaveOldMode);
ExitProcess(0);
}
VOID KeyEventProc(KEY_EVENT_RECORD ker)
{
printf("Key event: ");
if(ker.bKeyDown)
printf("key pressed");
else printf("key released");
}
VOID MouseEventProc(MOUSE_EVENT_RECORD mer)
{
#ifndef MOUSE_HWHEELED
#define MOUSE_HWHEELED 0x0008
#endif
gotoXY(33,6);
printf("Mouse event: ");
switch(mer.dwEventFlags)
{
case 0:
if(mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
{
gotoXY(46,6);
printf("left button pressed");
}
else if(mer.dwButtonState == RIGHTMOST_BUTTON_PRESSED)
{
gotoXY(46,6);
printf("right button pressed");
}
else
{
gotoXY(46,6);
printf("button press");
}
break;
case DOUBLE_CLICK:
gotoXY(46,6);
printf("double click");
break;
case MOUSE_HWHEELED:
gotoXY(46,6);
printf("horizontal mouse wheel");
break;
case MOUSE_MOVED:
gotoXY(46,6);
printf("mouse moved");
//gotoXY(12,13);
//GetMousePosWin();
break;
case MOUSE_WHEELED:
gotoXY(46,6);
printf("vertical mouse wheel");
break;
default:
gotoXY(46,6);
printf("unknown");
break;
}
}
// get Window pos through windows api
void GetMousePosWin(MOUSE_EVENT_RECORD mer)
{
int x,y;
// creates the handle i need to use
//HANDLE OutputH;
INPUT_RECORD Inrec;
DWORD evRead;
HANDLE hStdIn;
DWORD dwMode;
bool Captured=false;
hStdIn = GetStdHandle(STD_INPUT_HANDLE);
dwMode = ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT;
if( SetConsoleMode( hStdIn, dwMode | ENABLE_MOUSE_INPUT) == TRUE)
GetConsoleMode(hStdIn, &dwMode);
SetConsoleMode(hStdIn, (dwMode & (ENABLE_MOUSE_INPUT)));
// grab the handle to the console so i can use it
//OutputH = GetStdHandle(STD_OUTPUT_HANDLE);
//printf("Strated"); //Debug line.
do
{
PeekConsoleInput(hStdIn, &Inrec, 1, &evRead);
if( evRead )
{
ReadConsoleInput(hStdIn, &Inrec, 1, &evRead);
x= Inrec.Event.MouseEvent.dwMousePosition.X ;
y= Inrec.Event.MouseEvent.dwMousePosition.Y ;
switch (Inrec.EventType )
{
case MOUSE_EVENT:
{
Captured = true;
gotoXY(33,8);
std::cout << "x-> " << x << " ";
gotoXY(43,8);
std::cout << "y-> " << y << " ";
break;
}
}
}
}while(!Captured);
if((x==33 && y==10) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
{
gotoXY(47,10);
std::cout << "\xFB";
gotoXY(33,21);
std::cout << "You picked menu one";
Sleep(1200);
gotoXY(47,10);
std::cout << " ";
gotoXY(33,21);
std::cout << " ";
}
if((x==33 && y==12) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
{
gotoXY(47,12);
std::cout << "\xFB";
gotoXY(33,21);
std::cout << "You picked menu two";
Sleep(1200);
gotoXY(47,12);
std::cout << " ";
gotoXY(33,21);
std::cout << " ";
}
if((x==33 && y==14) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
{
gotoXY(47,14);
std::cout << "\xFB";
gotoXY(33,21);
std::cout << "You picked menu three";
Sleep(1200);
gotoXY(47,14);
std::cout << " ";
gotoXY(33,21);
std::cout << " ";
}
if((x==33 && y==16) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
{
gotoXY(40,16);
std::cout << "\xFB";
gotoXY(33,21);
std::cout << "You picked Quit";
Sleep(1200);
gotoXY(40,16);
std::cout << " ";
gotoXY(28,21);
exit(0);
}
}
VOID ResizeEventProc(WINDOW_BUFFER_SIZE_RECORD wbsr)
{
printf("Resize event\n");
printf("Console screen buffer is %d columns by %d rows.\n", wbsr.dwSize.X, wbsr.dwSize.Y);
}
void gotoXY(int x, int y)
{
CursorPosition.X = x;
CursorPosition.Y = y;
SetConsoleCursorPosition(console,CursorPosition);
}