Can anyone tell me how or help me to get a Window's Title and save it to a TXT file?

I tried couple of things with the GetWindowText() but only manage to get some numbers.

Wouldn't usually give away code, but it's just so small.

#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <iostream>
#include <fstream>

void saveCaption(HWND hwnd, char *filename) {
  int length = GetWindowTextLength( hwnd ) + 1;
  char *caption = new char[length];

  GetWindowText( hwnd, caption, length );

  std::ofstream out( filename );
  out << caption;

  delete[] caption;
}

int main() {
  saveCaption( GetConsoleWindow(), "caption.txt" );
}

Edited 7 Years Ago by William Hemsworth: n/a

Wouldn't usually give away code, but it's just so small.

#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <iostream>
#include <fstream>

void saveCaption(HWND hwnd, char *filename) {
  int length = GetWindowTextLength( hwnd ) + 1;
  char *caption = new char[length];

  GetWindowText( hwnd, caption, length );

  std::ofstream out( filename );
  out << caption;

  delete[] caption;
}

int main() {
  saveCaption( GetConsoleWindow(), "caption.txt" );
}

It gives an error:

error C2664: 'GetWindowTextW' : cannot convert parameter 2 from 'char *' to 'LPWSTR'

I set UNICODE to No Set in the compiling options and it works now but it doesn't save anything to the file why :o?

Either turn UNICODE off, or change the code to:

#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <iostream>
#include <fstream>

void saveCaption(HWND hwnd, TCHAR *filename) {
  int length = GetWindowTextLength( hwnd ) + 1;
  TCHAR *caption = new TCHAR[length];

  GetWindowText( hwnd, caption, length );

  std::wofstream out( filename );
  out << caption;

  delete[] caption;
}

int main() {
  saveCaption( GetConsoleWindow(), TEXT("caption.txt") );
}

Edited 7 Years Ago by William Hemsworth: n/a

Tried both ways It doesn't save anything to the output file :(. It is completely blank.

Tried both ways It doesn't save anything to the output file :(. It is completely blank.

I edited my post maybe before you tried that code, try again. There's no reason why that function shouldn't work, if it still doesn't work, show me the code you're using.

It works! It was my fault it wasn't working.

Now may I ask another question?
Imagine I put the console in the background does it gets the name of the window im currently typing? For example a browser or MSN...?

Solved I replaced GetConsoleWindow() with GetForegroundWindow().

Works perfectly Thanks! --- ALL SOLVED ---

This question has already been answered. Start a new discussion instead.