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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
// AllocateConsole1.cpp
// cl AllocateConsole1.cpp Kernel32.lib User32.lib Gdi32.lib /Feac2 /O1 /Os /MT /GA
// g++ AllocateConsole1.cpp -oac2.exe -mwindows -m64 -s -Os
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include <windows.h>
#include <stdio.h>
#include "AllocateConsole.h"
LRESULT CALLBACK fnWndProc_OnCreate(WndEventArgs& Wea)
{
HWND hButton=NULL;
Wea.hIns=((LPCREATESTRUCT)Wea.lParam)->hInstance;
hButton=CreateWindow(L"button",L"Show And Write To Console",WS_CHILD|WS_VISIBLE,90,50,200,30,Wea.hWnd,(HMENU)IDC_BUTTON1,Wea.hIns,0);
return 0;
}
LRESULT CALLBACK fnWndProc_OnCommand(WndEventArgs& Wea)
{
if(LOWORD(Wea.wParam)==IDC_BUTTON1)
{
HMENU hSysMenu = NULL;
HANDLE hStdOut = NULL;
int iWeight = 178;
DWORD dwCharsWritten = 0;
BOOL blnSuccess = FALSE;
wchar_t szBuffer[80];
blnSuccess=AllocConsole();
SetWindowLongPtr(Wea.hWnd,0,(LONG_PTR)blnSuccess); // Store success/failure of AllocConsole call at offset 0 of WNDCLASSEX::cbWndExtra bytes
if(blnSuccess)
{
hSysMenu=GetSystemMenu(GetConsoleWindow(),0);
DeleteMenu(hSysMenu,6,MF_BYPOSITION);
hStdOut=GetStdHandle(STD_OUTPUT_HANDLE);
wsprintf(szBuffer,L"My Name Is Fred And I Weight %d Pounds.\n",iWeight);
WriteConsole(hStdOut,szBuffer,wcslen(szBuffer),&dwCharsWritten,NULL);
}
}
return 0;
}
LRESULT CALLBACK fnWndProc_OnDestroy(WndEventArgs& Wea)
{
if(GetWindowLongPtr(Wea.hWnd,0))
FreeConsole();
PostQuitMessage(0);
return 0;
}
LRESULT CALLBACK fnWndProc(HWND hwnd, unsigned int msg, WPARAM wParam, LPARAM lParam)
{
WndEventArgs Wea;
for(unsigned int i=0; i<dim(EventHandler); i++)
{
if(EventHandler[i].iMsg==msg)
{
Wea.hWnd=hwnd, Wea.lParam=lParam, Wea.wParam=wParam;
return (*EventHandler[i].fnPtr)(Wea);
}
}
return (DefWindowProc(hwnd, msg, wParam, lParam));
}
int WINAPI WinMain(HINSTANCE hIns, HINSTANCE hPrevIns, LPSTR lpszArgument, int iShow)
{
wchar_t szClassName[]=L"AllocateConsole";
WNDCLASSEX wc;
MSG messages;
HWND hWnd;
wc.lpszClassName=szClassName; wc.lpfnWndProc=fnWndProc;
wc.cbSize=sizeof (WNDCLASSEX); wc.style=0;
wc.hIcon=LoadIcon(NULL,IDI_APPLICATION); wc.hInstance=hIns;
wc.hIconSm=NULL; wc.hCursor=LoadCursor(NULL,IDC_ARROW);
wc.hbrBackground=(HBRUSH)COLOR_BTNSHADOW; wc.cbWndExtra=sizeof(void*);
wc.lpszMenuName=NULL; wc.cbClsExtra=0;
RegisterClassEx(&wc);
hWnd=CreateWindowEx(0,szClassName,szClassName,WS_OVERLAPPEDWINDOW,775,575,400,190,HWND_DESKTOP,0,hIns,0);
ShowWindow(hWnd,iShow);
while(GetMessage(&messages,NULL,0,0))
{
TranslateMessage(&messages);
DispatchMessage(&messages);
}
return (int)messages.wParam;
}
| |