Can someone please tell me the problems with this piece of code? I'm bulding a windows app, not a console. Am I using the functions correctly. What types should I used? Okay I fixed semicolon err and else err? Still not working properly.
#include <windows.h>
int WINAPI WinMain(HINSTANCE thisin,HINSTANCE previn,LPSTR lpstr,INT int_)
{
LPTSTR buffer;
DWORD size;
SetConsoleTitle("Console Title");
if(!GetConsoleTitle(buffer,size))
cout << "error" << endl;
else cout << *buffer << endl;
system("Pause");
return 0;
}
It have 2 problems, first a ';' at end of if that is a C++ mistyping error and every body say it, but second is: for every API that get a buffer to return something, you should provide a valid buffer. Assume GetConsoleTitle
implemented as:
BOOL GetConsoleTitle(LPTSTR p, DWORD dwSize)
{
LPTSTR actualTitle = /* Get actual title from somewhere */;
while (dwSize--)
{
*p++ = *actualTitle++;
if (!*p++) return TRUE;
}
// Not enough buffer
return FALSE;
}
Now look at your program, you pass an uninitialized LPTSTR
to the function and as soon as API call *p++ = *actualTitle++
, it will cause a segmentation fault or Access violation
. so in order to solve it, you must pass a valid buffer as first argument and since LPTSTR
is a typedef of TCHAR*
you should have:
const DWORD dwSize = 128;
TCHAR buffer[dwSize];
if (GetConsoleTitle(buffer, dwSize)) std::cout << "OK!" << std::endl;
First thing is first. Your statement prints whether there is an error or not. Use an else there:
if(!GetConsoleTitle(buffer,size))
cout << "error" << endl;
else
cout << *buffer << endl;
and the ;
after your if
was a typo, I corrected it above.
You are using API's for Console App. Create a console app, copy this code to console project c or cpp source file and replace
int WINAPI WinMain(HINSTANCE thisin,HINSTANCE previn,LPSTR lpstr,INT int_)
with
int _tmain(int argc, char *argv[])
also remove ';' (semicolon) from 'if' statement.
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.