前言
看了下SFML的官方示例,发现SFML竟然还能这么玩
explicit RenderWindow(WindowHandle handle, const ContextSettings& settings = ContextSettings());
对,这个也是sf::RenderWindow的构造函数
typedef HWND__* WindowHandle;
由此可以看出,SFML可以把一个HWND当窗口使 (在官方示例里也确实把Static控件当sf::RenderWindow来用了)
代码
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <windows.h>
using namespace sf;
LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp);
HWND initWindow(HINSTANCE instance);
int main()
{
HINSTANCE instance = GetModuleHandle(NULL);
HWND hwnd = initWindow(instance);
RenderWindow window(hwnd);
RectangleShape rs(Vector2f(100,100));
rs.setFillColor(Color::Blue);
rs.setPosition(Vector2f(100,100));
MSG msg;
while(msg.message != WM_QUIT)
{
if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
window.clear();
window.draw(rs);
window.display();
}
}
return EXIT_SUCCESS;
}
LRESULT CALLBACK WndProc(HWND hwnd,UINT msg,WPARAM wp,LPARAM lp)
{
if(msg == WM_DESTROY)
{
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd,msg,wp,lp);
}
HWND initWindow(HINSTANCE instance)
{
WNDCLASSEX wc;
memset(&wc,0,sizeof(wc));
wc.cbSize = sizeof(wc);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.hInstance = instance;
wc.lpfnWndProc = WndProc;
wc.lpszClassName = "SFML Window";
wc.style = CS_HREDRAW|CS_VREDRAW;
RegisterClassEx(&wc);
return CreateWindowEx(WS_EX_WINDOWEDGE,"SFML Window","SFML Window",WS_VISIBLE|WS_SYSMENU,CW_USEDEFAULT,CW_USEDEFAULT,640,480,NULL,NULL,instance,NULL);
}
运行结果
突然发现SFGUI不香了
创建Win32控件
既然可以用HWND,那么能不能反过来呢? 其实是可以的 在看官方教程时发现sf::Window可以获取窗口句柄
WindowHandle getSystemHandle() const;
那么就能这样
#include <SFML/Graphics.hpp>
#include <windows.h>
using namespace sf;
int main()
{
HINSTANCE instance = GetModuleHandle(NULL);
Window window(VideoMode(640, 480), "SFML Window");
HWND hwnd = window.getSystemHandle();
HWND btn = CreateWindowEx(WS_EX_WINDOWEDGE, "Button", "Button", WS_VISIBLE | WS_CHILD | WS_BORDER | BS_CENTER, 0, 0, 100, 50, hwnd, NULL, instance, NULL);
HWND target = CreateWindowEx(WS_EX_WINDOWEDGE, "Static", NULL, WS_VISIBLE | WS_CHILD | WS_CLIPSIBLINGS, 0, 0, 640, 480, hwnd, NULL, instance, NULL);
RenderWindow display(target);
RectangleShape rs(Vector2f(100, 100));
rs.setFillColor(Color::Blue);
rs.setPosition(Vector2f(100, 100));
Event event;
while (window.isOpen())
{
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
{
window.close();
}
}
display.clear();
display.draw(rs);
display.display();
}
return EXIT_SUCCESS;
}
直接创建一个sf::Window,然后在里面添加控件 最后效果就是这样
总结
跟我一起大喊:SFML牛*! 以后写Win32程序干脆用SFML! 妙啊!
一些链接
官方示例 下载地址 官方教程
|