最近有个项目需要在一个指定的窗口上播放流视频,所以做了个ffmpeg+sdl的播放器,期间遇到个小问题,如何用sdl在指定的窗口上渲染呢?
网上查了半天,有人说在初始化sdl之前用SDL_putenv函数
char sdl_var[64];
sprintf(sdl_var, "SDL_WINDOWID=%d", hWnd);//主窗口句柄
SDL_putenv(sdl_var);
可是我的vs环境说找不到这个函数,不知道是什么原因,知道的兄弟可以评论告知一下.
也许是sdl 2.0后废弃了吧.
后来的解决方案是用SDL_CreateWindowFrom函数.
使用方法:
1.先获得窗口句柄.测试的话,可以使用visual studio的spy工具.高版本好像没有这个工具了.
下载地址:https://download.csdn.net/download/weixin_44117123/12686861
工具使用方法如下图
2.将sdl创建窗口的SDL_CreateWindow函数替换成以下语句:
HWND handle = (HWND)0x001B1A84; //这里是step1获得的句柄.
SDL_Window *window = SDL_CreateWindowFrom(handle);
完整代码:
#include
#include
#include
#pragma comment(lib,"SDL2.lib")
#pragma comment(lib,"SDL2main.lib")
extern "C"
{
#include "SDL.h"
}
int main(int argc, char* args[])
{
//窗口含有的surface
SDL_Surface* screenSurface = NULL;
//初始化SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
}
else {
//创建 window
//SDL_Window *window = SDL_CreateWindow("ShowPicture", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
HWND handle = (HWND)0x00090CA0; //获得的窗口句柄是00090CA0
SDL_Window *window = SDL_CreateWindowFrom(handle);
if (window == NULL)
{
printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
}
else {
//渲染层
SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
SDL_Surface *pic = SDL_LoadBMP("123.bmp");
//载入的图片生成SDL材质
SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, pic);
//把材质复制到渲染器
SDL_RenderCopy(renderer, texture, NULL, NULL);
//显示出来
SDL_RenderPresent(renderer);
bool quit = false;
SDL_Event event;
while (!quit)
{//主消息循环
SDL_WaitEvent(&event);
switch (event.type)
{
//用户从菜单要求退出程序
case SDL_QUIT:
quit = true;
break;
}
}
// 清理资源
SDL_DestroyTexture(texture);
SDL_FreeSurface(pic);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
}
}
//退出SDL
SDL_Quit();
return 0;
}
注:以上代码来源于互联网,我只是改了创建窗口的SDL_CreateWindow函数哈.