简体   繁体   中英

What is the "hwnd" that I need to pass to GetWindowRect? How do I get one?

Using CodeBlocks in Windows, I made a script for a game that reads screen pixels and determines a value depending of pixel colors , works great . But when I move my game screen it changes the coordinates of the pixels where I get the values from. I think I can use GetWindowRect to measure the corner of the game window and from there get the position of the pixels I need to view. If there's a better way of doing this I would appreciate the guidance. This is the example I try to compile. I get an error that "hwnd" is not declared.But I thought "hwnd" was part of the function. I found the function description here
https://msdn.microsoft.com/en-us/library/windows/desktop/ms633519(v=vs.85).aspx

#include <windows.h>

int main(){
    RECT rect;
    if(GetWindowRect(hwnd, &rect))
    {
        int width = rect.right - rect.left;
        int height = rect.bottom - rect.top;
    }
    std::cout<<width<<"\n"<<height;
}

After your definition of RECT rect;

Then try something like:

HWND hwnd = GetDesktopWindow();

That just demonstrates using the desktop window. In reality, you will use a HWND you receive from elsewhere.

In function "GetWindowRect(hwnd,&rect)" "hwnd" is the name of a variable that stores the handle to a window, and it's not defined. To declare "hwnd" use "HWND (variable name);" without parenthesis. To be able to get the handle of a window you need to use another function for example: FindWindow(NULL,TEXT("WindowName")); wich returns the handle to a window with that name or returns NULL if no window is found. After having a valid handle to a window "rect" wich is a Struct, will have the values of the position of that window. Those values will be "rect.top" wich is top "y" coordinate,"rect.bottom" wich is "y" bottom coordinate,"rect.left" wich is "x" left coordinate,"rect.right" wich is "x" right coordinate.
Screen Coordinates Image

Note!: in example Calculator must be open and not minimized!

Example:

 #include <windows.h>
 #include <iostream> 
 int main(){
 HWND handleToCalculatorWindow; // Handle to window declared here!
 RECT window;
 handleToCalculatorWindow = FindWindow(NULL,TEXT("Calculator"));
 GetWindowRect(handleToCalculatorWindow , &window); //Coordinates to window!
 std::cout<<"Calculator window top coordinate:"
 <<window.top<<"\nCalculator window right coordinate:"<<window.right;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM