Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to initialize Direct3D11 and create a window with specific background color with C++ Win32 API

2 Answers

0 votes
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX

#include <windows.h>
#include <d3d11_3.h>
#include <assert.h>

#pragma comment(lib, "d3d11.lib")

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam);

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 
{
    // Create a window
    HWND hwnd;
    {
        WNDCLASSEXW winClass = {};
        winClass.cbSize = sizeof(WNDCLASSEXW);
        winClass.style = CS_HREDRAW | CS_VREDRAW;
        winClass.lpfnWndProc = &WndProc;
        winClass.hInstance = hInstance;
        winClass.hCursor = LoadCursorW(0, IDC_ARROW);
        winClass.lpszClassName = L"WindowClassName";

        if (!RegisterClassEx(&winClass)) {
            MessageBoxA(0, "RegisterClassEx failed", "Fatal Error", MB_OK);
            return GetLastError();
        }

        RECT rect = { 0, 0, 1024, 768 };
        AdjustWindowRectEx(&rect, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_OVERLAPPEDWINDOW);
        LONG width = rect.right - rect.left;
        LONG height = rect.bottom - rect.top;

        hwnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW,
            winClass.lpszClassName,
            L"Direct3D 11 - Window With Backround Color",
            WS_OVERLAPPEDWINDOW | WS_VISIBLE,
            CW_USEDEFAULT, CW_USEDEFAULT,
            width,
            height,
            0, 0, hInstance, 0);

        if (!hwnd) {
            MessageBoxA(0, "CreateWindowEx failed", "Fatal Error", MB_OK);
            return GetLastError();
        }
    }

    // Create Direct3D 11 Device and Context
    ID3D11Device1* d3d11Device;
    ID3D11DeviceContext1* d3d11DeviceContext;
    {
        ID3D11Device* device;
        ID3D11DeviceContext* deviceContext;
        D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0 };
        UINT createDeviceBGRA = D3D11_CREATE_DEVICE_BGRA_SUPPORT;

        HRESULT hResult = D3D11CreateDevice(0, D3D_DRIVER_TYPE_HARDWARE,
            0, createDeviceBGRA,
            featureLevels, ARRAYSIZE(featureLevels),
            D3D11_SDK_VERSION, &device,
            0, &deviceContext);

        if (FAILED(hResult)) {
            MessageBoxA(0, "D3D11CreateDevice() failed", "Fatal Error", MB_OK);
            return GetLastError();
        }

        // Get interface of D3D11 Device and Context

        // A query interface queries information from the GPU
        hResult = device->QueryInterface(__uuidof(ID3D11Device1), (void**)&d3d11Device);
        assert(SUCCEEDED(hResult));
        device->Release();

        hResult = deviceContext->QueryInterface(__uuidof(ID3D11DeviceContext1), (void**)&d3d11DeviceContext);
        assert(SUCCEEDED(hResult));
        deviceContext->Release();
    }

    // Create Swap Chain
    IDXGISwapChain1* d3d11SwapChain;
    {
        IDXGIFactory2* dxgiFactory;
        {
            IDXGIDevice1* dxgiDevice;
            HRESULT hResult = d3d11Device->QueryInterface(__uuidof(IDXGIDevice1), (void**)&dxgiDevice);
            assert(SUCCEEDED(hResult));

            IDXGIAdapter* dxgiAdapter;
            // Get the adapter for the specified device.
            hResult = dxgiDevice->GetAdapter(&dxgiAdapter);
            assert(SUCCEEDED(hResult));
            dxgiDevice->Release();

            DXGI_ADAPTER_DESC adapterDesc;
            // Gets a DXGI description of an adapter (or video card)
            dxgiAdapter->GetDesc(&adapterDesc);

            OutputDebugStringA("(adapterDesc.Description) Graphics Device: ");
            OutputDebugStringW(adapterDesc.Description);

            hResult = dxgiAdapter->GetParent(__uuidof(IDXGIFactory2), (void**)&dxgiFactory);
            assert(SUCCEEDED(hResult));
            dxgiAdapter->Release();
        }

        DXGI_SWAP_CHAIN_DESC1 d3d11SwapChainDesc = {};
        d3d11SwapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
        d3d11SwapChainDesc.SampleDesc.Count = 1;
        d3d11SwapChainDesc.SampleDesc.Quality = 0;
        d3d11SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
        d3d11SwapChainDesc.BufferCount = 2;
        d3d11SwapChainDesc.Scaling = DXGI_SCALING_STRETCH;
        d3d11SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
        d3d11SwapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
        d3d11SwapChainDesc.Flags = 0;

        HRESULT hResult = dxgiFactory->CreateSwapChainForHwnd(d3d11Device, hwnd, &d3d11SwapChainDesc, 0, 0, &d3d11SwapChain);
        assert(SUCCEEDED(hResult));

        dxgiFactory->Release();
    }

    // Create Render Target View
    ID3D11RenderTargetView* d3d11FrameBufferView;
    {
        ID3D11Texture2D* d3d11FrameBuffer;
        HRESULT hResult = d3d11SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&d3d11FrameBuffer);
        assert(SUCCEEDED(hResult));

        // Creates a render-target view for accessing resource data
        hResult = d3d11Device->CreateRenderTargetView(d3d11FrameBuffer, 0, &d3d11FrameBufferView);
        assert(SUCCEEDED(hResult));
        d3d11FrameBuffer->Release();
    }

    bool running = true;
    while (running)
    {
        MSG msg = {};
        while (PeekMessageW(&msg, 0, 0, 0, PM_REMOVE)) {
            if (msg.message == WM_QUIT) {
                running = false;
            }
            TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }

        FLOAT backgroundColor[4] = { 0.3f, 0.7f, 0.3f, 1.0f };
        d3d11DeviceContext->ClearRenderTargetView(d3d11FrameBufferView, backgroundColor);

        d3d11SwapChain->Present(1, 0);
    }

    return 0;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    LRESULT result = 0;

    switch (msg) {
    case WM_KEYDOWN:
    {
        if (wparam == VK_ESCAPE) {
            DestroyWindow(hwnd);
        }
        break;
    }
    case WM_DESTROY:
    {
        PostQuitMessage(0);
        break;
    }
    default:
        result = DefWindowProcW(hwnd, msg, wparam, lparam);
    }

    return result;
}


/*
run:



*/

 



answered Aug 5, 2024 by avibootz
edited Aug 7, 2024 by avibootz
0 votes
#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <assert.h>
#include <d3d11_1.h>

#pragma comment(lib, "d3d11.lib")

LRESULT CALLBACK WndProc(HWND Window, UINT Message, WPARAM WParam, LPARAM LParam);

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 
{
    // Create a window

    WNDCLASS WindowClass = {};

    const wchar_t ClassName[] = L"WindowClassName";

    WindowClass.lpfnWndProc = WndProc;
    WindowClass.hInstance = hInstance;
    WindowClass.lpszClassName = ClassName;
    WindowClass.hCursor = LoadCursor(0, IDC_CROSS);

    if (!RegisterClass(&WindowClass)) {
        MessageBox(0, L"RegisterClass failed", 0, 0);
        return GetLastError();
    }

    HWND Window = CreateWindowEx(0, ClassName, L"Window",
        WS_OVERLAPPEDWINDOW | WS_VISIBLE,
        CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
        0, 0, hInstance, 0);

    if (!Window) {
        MessageBox(0, L"CreateWindowEx failed", 0, 0);
        return GetLastError();
    }

    // Create Direct3D 11 Device and Context
    ID3D11Device* DeviceCreated;
    ID3D11DeviceContext* DeviceContext;

    UINT flags = 0;

    D3D_FEATURE_LEVEL FeatureLevels[] = {
        D3D_FEATURE_LEVEL_11_0
    };

    /*
    HRESULT D3D11CreateDevice(
          [in, optional]  IDXGIAdapter            *pAdapter,
                          D3D_DRIVER_TYPE         DriverType,
                          HMODULE                 Software,
                          UINT                    Flags,
          [in, optional]  const D3D_FEATURE_LEVEL *pFeatureLevels,
                          UINT                    FeatureLevels,
                          UINT                    SDKVersion,
          [out, optional] ID3D11Device            **ppDevice,
          [out, optional] D3D_FEATURE_LEVEL       *pFeatureLevel,
          [out, optional] ID3D11DeviceContext     **ppImmediateContext
    );
    */

    HRESULT Result = D3D11CreateDevice(0, D3D_DRIVER_TYPE_HARDWARE, 0,
        flags, FeatureLevels,
        ARRAYSIZE(FeatureLevels),
        D3D11_SDK_VERSION, &DeviceCreated, 0,
        &DeviceContext);

    if (FAILED(Result)) {
        MessageBox(0, L"D3D11CreateDevice failed", 0, 0);
        return GetLastError();
    }

    ID3D11Device1* Device;
    ID3D11DeviceContext1* Context;

    Result = DeviceCreated->QueryInterface(__uuidof(ID3D11Device1), (void**)&Device);
    assert(SUCCEEDED(Result));
    DeviceCreated->Release();

    Result = DeviceContext->QueryInterface(__uuidof(ID3D11DeviceContext1), (void**)&Context);
    assert(SUCCEEDED(Result));
    DeviceContext->Release();
    
    // Create Swap Chain
    DXGI_SWAP_CHAIN_DESC1 SwapChainDesc = {};

    SwapChainDesc.Width = 0;
    SwapChainDesc.Height = 0;
    SwapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    SwapChainDesc.SampleDesc.Count = 1;
    SwapChainDesc.SampleDesc.Quality = 0;
    SwapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    SwapChainDesc.BufferCount = 1;
    SwapChainDesc.Scaling = DXGI_SCALING_STRETCH;
    SwapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    SwapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
    SwapChainDesc.Flags = 0;

    IDXGISwapChain1* SwapChain;

    IDXGIDevice2* DxgiDevice;
    Result = Device->QueryInterface(__uuidof(IDXGIDevice2), (void**)&DxgiDevice);
    assert(SUCCEEDED(Result));

    IDXGIAdapter* DxgiAdapter;
    Result = DxgiDevice->GetAdapter(&DxgiAdapter);
    assert(SUCCEEDED(Result));
    DxgiDevice->Release();

    IDXGIFactory2* DxgiFactory;
    Result = DxgiAdapter->GetParent(__uuidof(IDXGIFactory2), (void**)&DxgiFactory);
    assert(SUCCEEDED(Result));
    DxgiAdapter->Release();

    Result = DxgiFactory->CreateSwapChainForHwnd(Device, Window,
        &SwapChainDesc, 0, 0, &SwapChain);
    assert(SUCCEEDED(Result));
    DxgiFactory->Release();

    // Texture & RenderTargetView
    ID3D11Texture2D* Texture;
    Result = SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&Texture);
    assert(SUCCEEDED(Result));

    ID3D11RenderTargetView* RenderTargetView;
    Result = Device->CreateRenderTargetView(Texture, 0, &RenderTargetView);
    assert(SUCCEEDED(Result));
    Texture->Release();

    bool Running = true;

    while (Running) {
        MSG Message;
        while (PeekMessage(&Message, nullptr, 0, 0, PM_REMOVE)) {
            if (Message.message == WM_QUIT) Running = false;
            TranslateMessage(&Message);
            DispatchMessage(&Message);
        }

        float Color[4] = { 0.0f, 0.5f, 0.0f, 1.0f }; // Green
        Context->ClearRenderTargetView(RenderTargetView, Color);
        SwapChain->Present(1, 0);
    }

    return 0;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) 
{
    LRESULT result = 0;

    switch (msg) {
    case WM_KEYDOWN:
    {
        if (wparam == VK_ESCAPE) {
            DestroyWindow(hwnd);
        }
        break;
    }
    case WM_DESTROY:
    {
        PostQuitMessage(0);
        break;
    }
    default:
        result = DefWindowProcW(hwnd, msg, wparam, lparam);
    }

    return result;
}



/*
run:



*/

 



answered Aug 20, 2024 by avibootz
...