SDL2.0的下载可以参考这篇文章:。
本例开发环境:win7 64位 +VS2012 + SDL2.0.3 (stable)
第一步:新建MFC基于对话框的应用程序(此例工程命名为MFC_SDL),然后直接点击完成即可,如下图。
第二步:删除“TODO:在此放置对话框控件”。添加Picture Control和Button到对话框中,修改Button的名字为显示图片。
第三步:SDL相关头文件、lib库以及dll动态链接库的设置可以参考这篇文章:。
第四步:打开MFC_SDLDlg.cpp文件,在程序中添加头文件
- #include <SDL.h>
第五步:双击Button控件,转到鼠标点击响应程序。添加程序。程序如下:
- void CMFC_SDLDlg::OnBnClickedButton1()
- {
- // TODO: 在此添加控件通知处理程序代码
- //The window we'll be rendering to
- SDL_Window* gWindow = NULL;
- //The surface contained by the window
- SDL_Surface* gScreenSurface = NULL;
- //The image we will load and show on the screen
- SDL_Surface* gHelloWorld = NULL;
- //首先初始化
- if(SDL_Init(SDL_INIT_VIDEO)<0)
- {
- printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
- return ;
- }
- //创建窗口
- gWindow=SDL_CreateWindowFrom( (void *)( GetDlgItem(IDC_STATIC)->GetSafeHwnd() ) );
- if(gWindow==NULL)
- {
- printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
- return ;
- }
- //Use this function to get the SDL surface associated with the window.
- //获取窗口对应的surface
- gScreenSurface=SDL_GetWindowSurface(gWindow);
- //加载图片
- gHelloWorld = SDL_LoadBMP("Hello_World.bmp");//加载图片
- if( gHelloWorld == NULL )
- {
- printf( "Unable to load image %s! SDL Error: %s\n", "Hello_World.bmp", SDL_GetError() );
- return ;
- }
- //Use this function to perform a fast surface copy to a destination surface.
- //surface的快速复制
- // SDL_Surface* src ,const SDL_Rect* srcrect , SDL_Surface* dst , SDL_Rect* dstrect
- SDL_BlitSurface( gHelloWorld , NULL , gScreenSurface , NULL);
- SDL_UpdateWindowSurface(gWindow);//更新显示copy the window surface to the screen
- }
第六步:运行程序,点击“显示图片”按钮,现象如下:
从程序中可以看出,要将SDL窗口嵌入到MFC中很简单,只要将SDL原来创建窗口的函数:
- SDL_Window* gWindow = SDL_CreateWindow("SHOW BMP",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,SCREEN_WIDTH,SCREEN_HEIGHT,SDL_WINDOW_SHOWN);
改成下面的函数即可:
- SDL_Window* gWindow=SDL_CreateWindowFrom( (void *)( GetDlgItem(IDC_STATIC)->GetSafeHwnd() ) );
其中,IDC_STATIC为PictureControl的ID