I have the following C++ program written/borrowed that takes a screenshot of a window based on the window name.
When I run the program through a Windows command prompt, it works correctly. However, when I call the program in a TCL script with the exec command, it crashes the wish86 application.
Why does the program work through the command line, but not with the exec command?
Example: screenshot.exe calc.bmp "Calculator"
#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "gdiplus.lib")
using namespace Gdiplus;
// From http://msdn.microsoft.com/en-us/library/ms533843%28VS.85%29.aspx
int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
UINT num = 0; // number of image encoders
UINT size = 0; // size of the image encoder array in bytes
ImageCodecInfo* pImageCodecInfo = NULL;
GetImageEncodersSize(&num, &size);
if(size == 0)
return -1; // Failure
pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
if(pImageCodecInfo == NULL)
return -1; // Failure
GetImageEncoders(num, size, pImageCodecInfo);
for(UINT j = 0; j < num; ++j) {
if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 ) {
*pClsid = pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
return j; // Success
}
}
free(pImageCodecInfo);
return -1; // Failure
}
int wmain(int argc, wchar_t** argv)
{
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
HDC desktopdc;
HDC mydc;
HBITMAP mybmp;
desktopdc = GetDC(NULL);
if(desktopdc == NULL) {
return -1;
}
// If three arguments were passed, capture the specified window
if(argc == 3) {
RECT rc;
// Convert wchar_t[] to char[]
char title[512] = {0};
wcstombs(title, argv[2], wcslen(argv[2]));
HWND hwnd = FindWindow(NULL, title); //the window can't be min
if(hwnd == NULL) {
return -1;
}
GetWindowRect(hwnd, &rc);
mydc = CreateCompatibleDC(desktopdc);
mybmp = CreateCompatibleBitmap(desktopdc, rc.right - rc.left, rc.bottom - rc.top);
SelectObject(mydc,mybmp);
//Print to memory hdc
PrintWindow(hwnd, mydc, PW_CLIENTONLY);
} else {
// Capture the entire screen
int width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
int height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
mydc = CreateCompatibleDC(desktopdc);
mybmp = CreateCompatibleBitmap(desktopdc, width, height);
HBITMAP oldbmp = (HBITMAP)SelectObject(mydc, mybmp);
BitBlt(mydc,0,0,width,height,desktopdc,0,0, SRCCOPY|CAPTUREBLT);
SelectObject(mydc, oldbmp);
}
const wchar_t* filename = (argc > 1) ? argv[1] : L"screenshot.png";
Bitmap* b = Bitmap::FromHBITMAP(mybmp, NULL);
CLSID encoderClsid;
Status stat = GenericError;
if (b && GetEncoderClsid(L"image/png", &encoderClsid) != -1) {
stat = b->Save(filename, &encoderClsid, NULL);
}
if (b)
delete b;
// cleanup
GdiplusShutdown(gdiplusToken);
ReleaseDC(NULL, desktopdc);
DeleteObject(mybmp);
DeleteDC(mydc);
DeleteDC(desktopdc);
return stat == Ok;
}