How to include the value of getclassname() in if statement

Hi all, I would like to include the window class name into my if statement but I always get error. It is the issue of char and string but I tried several times still can't make it. Does anyone know how to solve this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<windows.h>
#include <tchar.h>
#include<iostream>
using namespace std;

int main() {

	HWND hWnd = FindWindowA(NULL,"Btn1");

	char class_name[100];

	GetClassNameA(hWnd,class_name, sizeof(class_name));

	if (class_name == 'Button'){
		MessageBox(NULL, _T("It's Button"), _T("Class Name"),MB_ICONERROR);
	}
	else{ 
		MessageBox(NULL, _T("It's not Button"), _T("Class Name"),MB_ICONERROR);
	}

	cout <<"Class name  : "<<class_name<<endl;

	system("PAUSE");
	return 0;

}
Last edited on
1
2
char* class_name;
(class_name == 'Button')

Two problems in that.

1. Single quotes contain one literal character. Button is not a character. It should be an array or characters.
Double quotes hold literal string: "Button"

2. The class_name is a pointer. String literal is accessed via a pointer. Two pointers are equal only if the point to same byte.
If you want to compare C-strings pointed to by pointers, then you have to C's functions.

If you want to use C++, then use std::string:
( std::string(class_name) == "Button" )
It works after replaced (class_name == 'Button') by (std::string(class_name) == "Button" ). Also, have to add #include<string> . Thanks!
Good. Can you explain why/how it works?
It convert char to string?
Yes.

The std::string(class_name) calls string constructor std::string(const char*) to create an unnamed temporary string object.
http://www.cplusplus.com/reference/string/string/string/

That constructor takes a pointer to C-string and initializes the string object with the pointed to C-string.

std::string has relational operators: http://www.cplusplus.com/reference/string/string/operators/

One of them is bool operator== (const string&, const char*);
Unnamed std::string object on the left and literal C-string constant on the right (the "Button") match that operator== and the operator computes whether they are equal.


However, the Microsoft API that forces you to use LPSTR and thus converting to std::string is extra work.
Perhaps the C way is acceptable: http://www.cplusplus.com/reference/cstring/strcmp/
1
2
3
#include <cstring>

if ( strcmp(class_name, "Button") == 0 )
Topic archived. No new replies allowed.