windows下实现窗口显示,如果限定是C/C++语言,并且是原生Windows支持,需要使用GDI或GDI+。一般是在Visual Studio里新建Win32应用程序,而不是Win32 console application(控制台程序),然后使用GDI的一些API,例如CreateWindow、CreateWindowEx来实现窗口的创建、显示等。
实际上MSDN官方并没有说只能是Win32应用程序,控制台程序完全可以。个人并不习惯WinMain()函数,更习惯main(int argc, char** argv)。例如OpenCV的highgui模块,它里面的cvNamedWindow(), cvShowImage(), cvWaitKey()这几个函数,在windows下的实现,如果不考虑其opengl版本的话,它是基于GDI实现的;而作为一个广泛使用的图像处理库,OpenCV源码中并没有WinMain函数。
下面是用纯C实现的“调用GDI的API接口,实现控制台类型程序中显示窗口”的样例程序,改编自How do you create a Win32 window from Console Application?
#include <stdio.h>
#include <windows.h>
LRESULT __stdcall WindowProcedure(HWND window, unsigned int msg, WPARAM wp, LPARAM lp)
{
switch(msg)
{
case WM_DESTROY:
printf("\ndestroying window\n");
PostQuitMessage(0) ;
return 0L ;
case WM_LBUTTONDOWN:
printf("\nmouse left button down at (%d, %d)\n", LOWORD(lp), HIWORD(lp));
// fall thru
default:
printf(".");
return DefWindowProc( window, msg, wp, lp ) ;
}
}
typedef struct MyRect{
int x, y, width, height;
} MyRect;
int main()
{
printf("hello world!\n");
const char* const myclass = "myclass" ;
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
/* Win 3.x */
wc.style = CS_DBLCLKS;
wc.lpfnWndProc = WindowProcedure;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = GetModuleHandle(0);
wc.hIcon = LoadIcon(0, IDI_APPLICATION);
wc.hCursor = LoadCursor(0, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = 0;
wc.lpszClassName = myclass;
/* Win 4.0 */
wc.hIconSm = LoadIcon(0, IDI_APPLICATION);
if(RegisterClassEx(&wc))
{
MyRect rect;
rect.x = 300;
rect.y = 300;
rect.width = 640;
rect.height = 480;
HWND window = CreateWindowEx( 0, myclass, "title",
WS_OVERLAPPEDWINDOW, rect.x, rect.y,
rect.width, rect.height, 0, 0, GetModuleHandle(0), 0 ) ;
if(window)
{
ShowWindow( window, SW_SHOWDEFAULT ) ;
MSG msg ;
while( GetMessage( &msg, 0, 0, 0 ) ) DispatchMessage(&msg);
}
}
}
原文地址:https://www.cnblogs.com/zjutzz/p/10806955.html
时间: 2024-11-08 13:06:36