notepad++ how to create dockable windows? - c++

I try to do a notepad++ plugin using C++. I need to do a dockable window in it. It should look like the search window in notepad++. I cant find a solution. So could you please help me?
Also I have the code "DockingFeature" which notepad++ provides me. However I cant create a dockable window.
//StaticDialog.h
#ifndef STATIC_DIALOG_H
#define STATIC_DIALOG_H
//#include "resource.h"
#include "Window.h"
#include "Notepad_plus_msgs.h"
enum PosAlign{ALIGNPOS_LEFT, ALIGNPOS_RIGHT, ALIGNPOS_TOP, ALIGNPOS_BOTTOM};
struct DLGTEMPLATEEX {
WORD dlgVer;
WORD signature;
DWORD helpID;
DWORD exStyle;
DWORD style;
WORD cDlgItems;
short x;
short y;
short cx;
short cy;
// The structure has more fields but are variable length
} ;
class StaticDialog : public Window
{
public :
StaticDialog() : Window() {};
~StaticDialog(){
if (isCreated()) {
::SetWindowLongPtr(_hSelf, GWL_USERDATA, (long)NULL); //Prevent run_dlgProc from doing anything, since its virtual
destroy();
}
};
virtual void create(int dialogID, bool isRTL = false);
virtual bool isCreated() const {
return (_hSelf != NULL);
};
void goToCenter();
void destroy() {
::SendMessage(_hParent, NPPM_MODELESSDIALOG, MODELESSDIALOGREMOVE, (WPARAM)_hSelf);
::DestroyWindow(_hSelf);
};
protected :
RECT _rc;
static BOOL CALLBACK dlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
virtual BOOL CALLBACK run_dlgProc(UINT message, WPARAM wParam, LPARAM lParam) = 0;
void alignWith(HWND handle, HWND handle2Align, PosAlign pos, POINT & point);
HGLOBAL makeRTLResource(int dialogID, DLGTEMPLATE **ppMyDlgTemplate);
};
#endif //STATIC_DIALOG_H
//staticDialog.cpp
#include "StaticDialog.h"
void StaticDialog::goToCenter()
{
RECT rc;
::GetClientRect(_hParent, &rc);
POINT center;
center.x = rc.left + (rc.right - rc.left)/2;
center.y = rc.top + (rc.bottom - rc.top)/2;
::ClientToScreen(_hParent, &center);
int x = center.x - (_rc.right - _rc.left)/2;
int y = center.y - (_rc.bottom - _rc.top)/2;
::SetWindowPos(_hSelf, HWND_TOP, x, y, _rc.right - _rc.left, _rc.bottom - _rc.top, SWP_SHOWWINDOW);
}
HGLOBAL StaticDialog::makeRTLResource(int dialogID, DLGTEMPLATE **ppMyDlgTemplate)
{
// Get Dlg Template resource
HRSRC hDialogRC = ::FindResource(_hInst, MAKEINTRESOURCE(dialogID), RT_DIALOG);
HGLOBAL hDlgTemplate = ::LoadResource(_hInst, hDialogRC);
DLGTEMPLATE *pDlgTemplate = (DLGTEMPLATE *)::LockResource(hDlgTemplate);
// Duplicate Dlg Template resource
unsigned long sizeDlg = ::SizeofResource(_hInst, hDialogRC);
HGLOBAL hMyDlgTemplate = ::GlobalAlloc(GPTR, sizeDlg);
*ppMyDlgTemplate = (DLGTEMPLATE *)::GlobalLock(hMyDlgTemplate);
::memcpy(*ppMyDlgTemplate, pDlgTemplate, sizeDlg);
DLGTEMPLATEEX *pMyDlgTemplateEx = (DLGTEMPLATEEX *)*ppMyDlgTemplate;
if (pMyDlgTemplateEx->signature == 0xFFFF)
pMyDlgTemplateEx->exStyle |= WS_EX_LAYOUTRTL;
else
(*ppMyDlgTemplate)->dwExtendedStyle |= WS_EX_LAYOUTRTL;
return hMyDlgTemplate;
}
void StaticDialog::create(int dialogID, bool isRTL)
{
if (isRTL)
{
DLGTEMPLATE *pMyDlgTemplate = NULL;
HGLOBAL hMyDlgTemplate = makeRTLResource(dialogID, &pMyDlgTemplate);
_hSelf = ::CreateDialogIndirectParam(_hInst, pMyDlgTemplate, _hParent, (DLGPROC)dlgProc, (LPARAM)this);
::GlobalFree(hMyDlgTemplate);
}
else
_hSelf = ::CreateDialogParam(_hInst, MAKEINTRESOURCE(dialogID), _hParent, (DLGPROC)dlgProc, (LPARAM)this);
if (!_hSelf)
{
return;
}
::SendMessage(_hParent, NPPM_MODELESSDIALOG, MODELESSDIALOGADD, (WPARAM)_hSelf);
}
BOOL CALLBACK StaticDialog::dlgProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG :
{
StaticDialog *pStaticDlg = (StaticDialog *)(lParam);
pStaticDlg->_hSelf = hwnd;
::SetWindowLongPtr(hwnd, GWL_USERDATA, (long)lParam);
::GetWindowRect(hwnd, &(pStaticDlg->_rc));
pStaticDlg->run_dlgProc(message, wParam, lParam);
return TRUE;
}
default :
{
StaticDialog *pStaticDlg = (StaticDialog *)(::GetWindowLongPtr(hwnd, GWL_USERDATA));
if (!pStaticDlg)
return FALSE;
return pStaticDlg->run_dlgProc(message, wParam, lParam);
}
}
}
void StaticDialog::alignWith(HWND handle, HWND handle2Align, PosAlign pos, POINT & point)
{
RECT rc, rc2;
::GetWindowRect(handle, &rc);
point.x = rc.left;
point.y = rc.top;
switch (pos)
{
case ALIGNPOS_LEFT :
::GetWindowRect(handle2Align, &rc2);
point.x -= rc2.right - rc2.left;
break;
case ALIGNPOS_RIGHT :
::GetWindowRect(handle, &rc2);
point.x += rc2.right - rc2.left;
break;
case ALIGNPOS_TOP :
::GetWindowRect(handle2Align, &rc2);
point.y -= rc2.bottom - rc2.top;
break;
default : //ALIGNPOS_BOTTOM
::GetWindowRect(handle, &rc2);
point.y += rc2.bottom - rc2.top;
break;
}
::ScreenToClient(_hSelf, &point);
}

Related

Why is D3Dcompiler_43.dll Loaded and Unloaded every frame (huge performance hit), but it only happens when I have two windows of different sizes open?

Why is D3Dcompiler_43.dll Loaded and Unloaded every frame?
Why does my two window direct-X 11 application drop from 2000 Hz to 12 Hz when I resize one of the windows?
In simplified sample I have attached code from, it starts with two identical sized windows at 2000 Hz, but if I change the size of either one, the frame rate of both goes to 12 Hz.
If I minimize either one, I get back to full speed, 4000Hz with one window.
When it is running at 12 Hz, I get the following Output Trace EVERY FRAME:
'Galaxies.exe' (Win32): Loaded 'C:\Windows\System32\D3Dcompiler_43.dll'
'Galaxies.exe' (Win32): Unloaded 'C:\Windows\System32\D3Dcompiler_43.dll'
This trace comes out when I call IDGXISwapChain->Present().
This trace does not come out when running 2000Hz.
I do not expect to need D3Dcompiler_43.dll at all, since I build my shaders at compile time, not run time. But if it did need it, then it should load it and keep it, not load each frame.
And if I make the window sizes match again, or minimize one, then the trace stops.
C++, Directx 11
My basic template is based on the Microsoft Sample "SimpleTexturePC".
Main changes from that template:
compile textures into program rather than reading at run time
compile shaders into program rather than reading at run time
extend DeviceResources to be able to support more than one window
by making arrays for all the resources, such as RenderTargetView
Extending Main.cpp to create more than one window, and have a WinProc for each.
Each of these unique WinProcs then calls a WinProcCommon with an "index" that identifies the window.
Adding a second camera for use on 2nd window
Adding a trace to the main application "Galaxies.cpp" so I could see the FPS.
(the rest of the main application behavior is not in simplified sample).
Main.cpp
//
// Main.cpp
//
#include ...
namespace
{
std::unique_ptr<Galaxies> g_game_p;
};
LPCWSTR g_szAppName0 = L"World1";
LPCWSTR g_szAppName1 = L"World2";
LPCWSTR g_szAppName2 = L"World3";
LRESULT CALLBACK WndProcWorld1(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK WndProcWorld2(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK WndProcWorld3(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK WndProcCommon(UINT, HWND, UINT, WPARAM, LPARAM);
// Entry point
int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
if (!XMVerifyCPUSupport())
return 1;
HRESULT hr = CoInitializeEx(nullptr, COINITBASE_MULTITHREADED);
if (FAILED(hr))
return 1;
g_game_p = std::make_unique<Galaxies>();
int border = getInvisableBorderWidth();
// Register / create window 1
{
// Register class
WNDCLASSEXW wcex = {};
wcex.cbSize = sizeof(WNDCLASSEXW);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProcWorld1;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIconW(hInstance, L"IDI_ICON1");
wcex.hCursor = LoadCursorW(nullptr, IDC_ARROW);
wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
wcex.lpszClassName = L"WindowClass1";
wcex.hIconSm = LoadIconW(wcex.hInstance, L"IDI_ICON1");
if (!RegisterClassExW(&wcex)) // W implies unicode version.
return 1;
// Create window
int w, h;
g_game_p->GetDefaultWindowSize(w, h);
HWND hwnd = CreateWindowExW(0, wcex.lpszClassName, g_szAppName0, WS_OVERLAPPEDWINDOW,
50 - border, 50, w, h, nullptr, nullptr, hInstance, nullptr);
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(g_game_p.get()));
if (!hwnd)
return 1;
g_game_p->Initialize(kGameWindow1, hwnd, w, h); // this chooses non-fullscreen location, though we will go full screen in a sec...
ShowWindow(hwnd, SW_SHOWNORMAL);
}
// Register / create window 2
{
// Register class
WNDCLASSEXW wcex = {};
wcex.cbSize = sizeof(WNDCLASSEXW);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProcWorld2;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIconW(hInstance, L"IDI_ICON2");
wcex.hCursor = LoadCursorW(nullptr, IDC_ARROW);
wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
wcex.lpszClassName = L"WindowClass2";
wcex.hIconSm = LoadIconW(wcex.hInstance, L"IDI_ICON2");
if (!RegisterClassExW(&wcex)) // W implies unicode version.
return 1;
// Create window
int w, h;
g_game_p->GetDefaultWindowSize(w, h);
HWND hwnd = CreateWindowExW(0, wcex.lpszClassName, g_szAppName1, WS_OVERLAPPEDWINDOW,
100 - border, 100, w + 00, h + 00, nullptr, nullptr, hInstance, nullptr);
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(g_game_p.get()));
if (!hwnd)
return 1;
g_game_p->Initialize(kGameWindow2, hwnd, w, h);
ShowWindow(hwnd, SW_SHOWNORMAL);
}
// Main message loop
MSG msg = {};
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
g_game_p->Tick();
}
}
g_game_p.reset();
CoUninitialize();
return static_cast<int>(msg.wParam);
}
// First parameter "index" used to differentiate the three windows.
LRESULT CALLBACK WndProcCommon(UINT index, HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
WindowStruct& winInfo = g_deviceResources_p->GetWindowStruct(index);
auto galaxies_p = reinterpret_cast<Galaxies*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
switch (message)
{
case WM_PAINT:
if (winInfo.in_sizemove && galaxies_p)
{
RECT rc;
GetWindowRect(hWnd, &rc);
galaxies_p->OnWindowSizeChanged(index, rc.right - rc.left, rc.bottom - rc.top);
galaxies_p->Tick();
}
else
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
break;
case WM_MOVE:
if (galaxies_p)
{
galaxies_p->OnWindowMoved(index);
}
break;
case WM_SIZE:
if (wParam == SIZE_MINIMIZED)
{
if (!winInfo.minimized)
{
winInfo.minimized = true;
if (!winInfo.in_suspend && galaxies_p)
galaxies_p->OnSuspending();
winInfo.in_suspend = true;
}
}
else if (winInfo.minimized)
{
winInfo.minimized = false;
if (winInfo.in_suspend && galaxies_p)
galaxies_p->OnResuming();
winInfo.in_suspend = false;
}
else if (!winInfo.in_sizemove && galaxies_p)
{
RECT rc;
GetWindowRect(hWnd, &rc);
galaxies_p->OnWindowSizeChanged(index, rc.right - rc.left, rc.bottom - rc.top);
}
break;
case WM_ENTERSIZEMOVE:
winInfo.in_sizemove = true;
break;
case WM_EXITSIZEMOVE:
winInfo.in_sizemove = false;
if (galaxies_p)
{
RECT rc;
GetWindowRect(hWnd, &rc);
galaxies_p->OnWindowSizeChanged(index, rc.right - rc.left, rc.bottom - rc.top);
}
break;
case WM_GETMINMAXINFO:
if (lParam)
{
auto info = reinterpret_cast<MINMAXINFO*>(lParam);
info->ptMinTrackSize.x = 320;
info->ptMinTrackSize.y = 200;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case ... mouse cases
Mouse::ProcessMessage(message, wParam, lParam);
break;
case WM_KEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
Keyboard::ProcessMessage(message, wParam, lParam);
break;
case WM_MENUCHAR:
return MAKELRESULT(0, MNC_CLOSE);
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
// Windows procedure x3
LRESULT CALLBACK WndProcWorld1(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
return WndProcCommon(kGameWindow1, hWnd, message, wParam, lParam);
}
LRESULT CALLBACK WndProcWorld2(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
return WndProcCommon(kGameWindow2, hWnd, message, wParam, lParam);
}
LRESULT CALLBACK WndProcWorld3(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
return WndProcCommon(kGameWindow3, hWnd, message, wParam, lParam);
}
// Exit helper
void ExitGame() noexcept
{
PostQuitMessage(0);
}
Galaxies.cpp
//
// Galaxies.cpp
//
#include ...
// Global variables
std::unique_ptr<DX::StepTimer> g_timer_p;
std::unique_ptr<DX::DeviceResources> g_deviceResources_p;
std::unique_ptr<DirectX::CommonStates> g_states_p;
std::unique_ptr<padInput> g_input_p;
std::unique_ptr<Camera> g_camera_p[2];
std::unique_ptr<HudText> g_text_p;
Galaxies::Galaxies() noexcept(false)
{
g_deviceResources_p = std::make_unique<DX::DeviceResources>(DXGI_FORMAT_B8G8R8A8_UNORM_SRGB);
g_deviceResources_p->RegisterDeviceNotify(this);
}
void Galaxies::Initialize(UINT index, HWND window, int width, int height)
{
static int once = true;
if (once)
{
g_deviceResources_p->CreateDeviceResources();
once = false;
}
switch (index)
{
case kGameWindow1:
{
g_timer_p = std::make_unique<DX::StepTimer>();
g_input_p = std::make_unique<padInput>();
g_camera_p[0] = std::make_unique<Camera>();
g_camera_p[1] = std::make_unique<Camera>();
g_text_p = std::make_unique<HudText>();
// PER OBJECT INITIALIZE
g_camera_p[0]->Initialize(0);
g_camera_p[1]->Initialize(1);
g_input_p ->Initialize();
g_text_p ->Initialize();
g_deviceResources_p->SetWindow(index, window, width, height);
g_deviceResources_p->CreateWindowSizeDependentResources(index);
OnDeviceRestored();
break;
}
case kGameWindow2:
case kGameWindow3:
default:
{
g_deviceResources_p->SetWindow(index, window, width, height);
g_deviceResources_p->CreateWindowSizeDependentResources(index);
break;
}
}
}
void Galaxies::GetDefaultWindowSize(int& width, int& height) const noexcept
{
...
}
void Galaxies::OnDeviceLost()
{
g_states_p.reset();
m_spPerFrameConstantBuffer.Reset();
g_text_p->OnDeviceLost();
}
void Galaxies::OnDeviceRestored()
{
CreateDeviceDependentResources();
CreateWindowSizeDependentResources(0);
CreateWindowSizeDependentResources(1);
WindowSizeChangeConfirmed(0);
WindowSizeChangeConfirmed(1);
g_text_p->OnDeviceRestored();
}
void Galaxies::OnSuspending()
{
}
void Galaxies::OnResuming()
{
g_timer_p->ResetElapsedTime();
}
void Galaxies::OnWindowMoved(UINT index)
{
auto r = g_deviceResources_p->GetOutputSize(index);
g_deviceResources_p->WindowSizeChanged(index, r.width, r.height);
}
// Pass in CURRENT (Last known) window size (icluding frame), so we can compare that with current size
// as read in deviceResources.
void Galaxies::OnWindowSizeChanged(UINT index, int width, int height)
{
// returns false if size unchanged
if (g_deviceResources_p->WindowSizeChanged(index, width, height))
{
CreateWindowSizeDependentResources(0);
WindowSizeChangeConfirmed(index);
}
}
void Galaxies::Tick()
{
UpdateRenderGPUTextures();
g_timer_p->Tick([&]()
{
UpdateInput();
UpdateCameras();
UpdateWorld();
});
RenderWorld(0);
if (!g_deviceResources_p->isWindowMinimized(1))
{
RenderWorld(1);
}
}
void Galaxies::Clear(int index)
{
// Clear the views.
auto context = g_deviceResources_p->GetD3DDeviceContext();
auto renderTargetView = g_deviceResources_p->GetRenderTargetView(index);
auto depthStencilView = g_deviceResources_p->GetDepthStencilView(index);
context->ClearRenderTargetView(renderTargetView, Colors::Black);
context->ClearDepthStencilView(depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
}
void Galaxies::CreateDeviceDependentResources()
{
auto device = g_deviceResources_p->GetD3DDevice();
g_states_p = std::make_unique<CommonStates>(device);
// Create constant buffers.
D3D11_BUFFER_DESC bufferDesc = {};
bufferDesc.Usage = D3D11_USAGE_DYNAMIC;
bufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bufferDesc.MiscFlags = 0;
bufferDesc.ByteWidth = sizeof(PerFrameConstantBuffer);
DX::ThrowIfFailed(device->CreateBuffer(&bufferDesc, nullptr, m_spPerFrameConstantBuffer.ReleaseAndGetAddressOf()));
}
// Allocate all memory resources that change on a window SizeChanged event.
void Galaxies::CreateWindowSizeDependentResources(UINT index)
{
// TODO: Initialize windows-size dependent objects here.
}
void Galaxies::UpdateRenderGPUTextures()
{
// Don't try to render anything before the first Update.
if (g_timer_p->GetFrameCount() == 0)
{
return;
}
}
void Galaxies::UpdateInput()
{
g_input_p->Update();
if (g_input_p->isKeyDownEdge(escape))
{
ExitGame();
}
}
void Galaxies::UpdateCameras()
{
g_camera_p[0]->Update();
// g_camera_p[1]->Update();
}
// Updates the world.
void Galaxies::UpdateWorld()
{
}
void Galaxies::RenderWorld(int index) // index 0, 1. not 2 (not edit window)
{
if (g_timer_p->GetFrameCount() == 0)
{
return;
}
Clear(index);
// Update Constants Buffer with per-frame variables.
// Though I now do this up to 3 times per frame - once per window.
auto context = g_deviceResources_p->GetD3DDeviceContext();
auto d3dBuffer = m_spPerFrameConstantBuffer.Get();
// Exclude 3rd window for now
if (index != 2)
{ // PRE-LOCK
MapGuard mappedResource(context, d3dBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0);
PerFrameConstantBuffer* data = reinterpret_cast<PerFrameConstantBuffer*>(mappedResource.get());
g_camera_p[index]->GetPerFrameData(data);
data->frameTime = g_timer_p->GetElapsedSeconds();
if (g_input_p->isButtonToggleSet(leftShoulder))
{
data->frameTime *= 5;
}
data->totalTime = g_timer_p->GetTotalSeconds();
int fps = (int)g_timer_p->GetFramesPerSecond();
char buffer[TEXT_NUM_OF_CHAR];
memset(buffer, 127, sizeof(buffer));
if (index == 0)
{
snprintf(&buffer[0 * TEXT_NUM_CHAR_PER_ROW], TEXT_NUM_CHAR_PER_ROW + 1, "Window 1 ");
}
else
{
snprintf(&buffer[0 * TEXT_NUM_CHAR_PER_ROW], TEXT_NUM_CHAR_PER_ROW + 1, "Window 2 ");
}
snprintf(&buffer[TEXT_NUM_CHAR_PER_ROW], TEXT_NUM_CHAR_PER_ROW + 1, "Galaxies V0.01 ");
snprintf(&buffer[2 * TEXT_NUM_CHAR_PER_ROW], TEXT_NUM_CHAR_PER_ROW + 1, " FPS = %d ", fps);
for (int i = 0; i < TEXT_NUM_OF_CHAR; i++)
{
data->alpha[4 * i] = buffer[i] - 0x20; // 0x20 is the first ascii char in our texture atlas. It is " "
}
} // UNLOCK (in mappedResource destructor)
context->VSSetConstantBuffers(CONSTANTS_PER_FRAME, 1, &d3dBuffer);
context->PSSetConstantBuffers(CONSTANTS_PER_FRAME, 1, &d3dBuffer);
auto renderTargetView = g_deviceResources_p->GetRenderTargetView(index);
auto depthStencilView = g_deviceResources_p->GetDepthStencilView(index);
context->OMSetRenderTargets(1, &renderTargetView, depthStencilView);
// Set the viewport.
auto viewport = g_deviceResources_p->GetScreenViewport(index);
context->RSSetViewports(1, &viewport);
if (index != 2)
{
g_text_p->Render();
}
g_deviceResources_p->Present(index);
}
void Galaxies::WindowSizeChangeConfirmed(UINT index)
{
auto size = g_deviceResources_p->GetOutputSize(index);
switch (index)
{
case (kGameWindow1):
g_camera_p[0]->OnWindowSizeChanged(size.width, size.height);
g_text_p ->OnWindowSizeChanged(size.width, size.height);
break;
case (kGameWindow2):
g_camera_p[1]->OnWindowSizeChanged(size.width, size.height);
break;
case (kGameWindow3):
break;
default:
break;
}
}
DeviceResources.cpp
//
// DeviceResources.cpp
//
#include ...
using namespace DirectX;
using namespace DX;
using Microsoft::WRL::ComPtr;
DeviceResources::DeviceResources(
DXGI_FORMAT backBufferFormat,
DXGI_FORMAT depthBufferFormat,
UINT backBufferCount,
D3D_FEATURE_LEVEL minFeatureLevel,
unsigned int flags) noexcept :
m_backBufferFormat{ backBufferFormat },
m_depthBufferFormat{ depthBufferFormat },
m_backBufferCount{backBufferCount},
m_d3dMinFeatureLevel(minFeatureLevel),
m_window(),
m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1),
m_colorSpace(DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709),
m_options(flags | c_FlipPresent | c_AllowTearing),
m_deviceNotify(nullptr)
{
m_windowCount = 0;
for (int index = 0; index < c_MaxWindows; index++)
{
m_window[index] = nullptr;
m_WindowStruct[index] = WindowStruct();
m_screenViewport[index] = { 100, 100, 800, 600, 0, 1 };
}
}
void DeviceResources::CreateDeviceResources()
{
UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;
CreateFactory();
...
// Determine feature levels
...
ComPtr<IDXGIAdapter1> adapter;
GetHardwareAdapter(adapter.GetAddressOf());
// Create the Direct3D 11 API device / context.
ComPtr<ID3D11Device> device;
ComPtr<ID3D11DeviceContext> context;
HRESULT hr = E_FAIL;
if (adapter)
{
hr = D3D11CreateDevice(
adapter.Get(),
D3D_DRIVER_TYPE_UNKNOWN,
nullptr,
creationFlags,
s_featureLevels,
featLevelCount,
D3D11_SDK_VERSION,
device.GetAddressOf(),
&m_d3dFeatureLevel,
context.GetAddressOf()
);
}
if (FAILED(hr))
{
// fall back to WARP device.
...
}
ThrowIfFailed(hr);
ThrowIfFailed(device.As(&m_d3dDevice));
ThrowIfFailed(context.As(&m_d3dContext));
}
// recreate every time the window size is changed.
void DeviceResources::CreateWindowSizeDependentResources(UINT index)
{
if (!m_window[index])
{
throw std::exception("need valid window handle");
}
// Clear the previous window size specific context.
ID3D11RenderTargetView* nullViews[] = { nullptr };
m_d3dContext->OMSetRenderTargets(_countof(nullViews), nullViews, nullptr);
m_d3dRenderTargetView[index].Reset();
m_d3dDepthStencilView[index].Reset();
m_renderTargetTexture[index].Reset();
m_depthStencilTexture[index].Reset();
m_d3dContext->Flush();
// Determine the render target size in pixels.
const UINT backBufferWidth = std::max<UINT>(static_cast<UINT>(m_WindowStruct[index].currentPos.width), 1u);
const UINT backBufferHeight = std::max<UINT>(static_cast<UINT>(m_WindowStruct[index].currentPos.height), 1u);
const DXGI_FORMAT backBufferFormat = (m_options & (c_FlipPresent | c_AllowTearing | c_EnableHDR)) ? NoSRGB(m_backBufferFormat) : m_backBufferFormat;
if (m_swapChain[index])
{
// If the swap chain already exists, resize it.
HRESULT hr = m_swapChain[index]->ResizeBuffers(
m_backBufferCount,
backBufferWidth,
backBufferHeight,
backBufferFormat,
(m_options & c_AllowTearing) ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0u
);
if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
{
...
}
else
{
ThrowIfFailed(hr);
}
}
else
{
// Create a descriptor for the swap chain.
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
swapChainDesc.Width = backBufferWidth;
swapChainDesc.Height = backBufferHeight;
swapChainDesc.Format = backBufferFormat;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.BufferCount = m_backBufferCount;
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
swapChainDesc.Scaling = DXGI_SCALING_STRETCH;
swapChainDesc.SwapEffect = (m_options & (c_FlipPresent | c_AllowTearing | c_EnableHDR)) ? DXGI_SWAP_EFFECT_FLIP_DISCARD : DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
swapChainDesc.Flags = (m_options & c_AllowTearing) ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0u;
DXGI_SWAP_CHAIN_FULLSCREEN_DESC fsSwapChainDesc = {};
fsSwapChainDesc.Windowed = TRUE;
// Create a SwapChain
ThrowIfFailed(m_dxgiFactory->CreateSwapChainForHwnd(
m_d3dDevice.Get(),
m_window[index],
&swapChainDesc,
&fsSwapChainDesc,
nullptr, m_swapChain[index].ReleaseAndGetAddressOf()
));
ThrowIfFailed(m_dxgiFactory->MakeWindowAssociation(m_window[index], DXGI_MWA_NO_ALT_ENTER));
}
// Create a render target view of the swap chain back buffer.
ThrowIfFailed(m_swapChain[index]->GetBuffer(0, IID_PPV_ARGS(m_renderTargetTexture[index].ReleaseAndGetAddressOf())));
CD3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc(D3D11_RTV_DIMENSION_TEXTURE2D, m_backBufferFormat);
ThrowIfFailed(m_d3dDevice->CreateRenderTargetView(
m_renderTargetTexture[index].Get(),
&renderTargetViewDesc,
m_d3dRenderTargetView[index].ReleaseAndGetAddressOf()
));
if (m_depthBufferFormat != DXGI_FORMAT_UNKNOWN)
{
// Create a depth stencil view for use with 3D rendering if needed.
CD3D11_TEXTURE2D_DESC depthStencilDesc(
m_depthBufferFormat,
backBufferWidth,
backBufferHeight,
1,
1,
D3D11_BIND_DEPTH_STENCIL
);
ThrowIfFailed(m_d3dDevice->CreateTexture2D(
&depthStencilDesc,
nullptr,
m_depthStencilTexture[index].ReleaseAndGetAddressOf()
));
CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D);
ThrowIfFailed(m_d3dDevice->CreateDepthStencilView(
m_depthStencilTexture[index].Get(),
&depthStencilViewDesc,
m_d3dDepthStencilView[index].ReleaseAndGetAddressOf()
));
}
// Set the 3D rendering viewport
m_screenViewport[index] = CD3D11_VIEWPORT(
0.0f,
0.0f,
static_cast<float>(backBufferWidth),
static_cast<float>(backBufferHeight)
);
}
void DeviceResources::SetWindow(UINT index, HWND window, int width, int height) noexcept
{
m_window[index] = window;
int indent = 50 * (index + 1);
RECTxywh windowPos = { indent - getInvisableBorderWidth(), indent, width, height };
m_WindowStruct[index].setWindowedByWindowPos(windowPos, 0, true);
}
bool DeviceResources::WindowSizeChanged(UINT index, int width, int height)
{
RECTxywh newRc = { 0, 0, width, height };
RECTxywh oldRc = { 0, 0, m_WindowStruct[index].currentPos.width, m_WindowStruct[index].currentPos.height };
if (newRc == oldRc)
{
// i.e. size didnt actually change
return false;
}
m_WindowStruct[index].setWindowedByWindowPos(newRc, 0, false);
CreateWindowSizeDependentResources(index);
return true;
}
// Recreate all device resources
void DeviceResources::HandleDeviceLost(UINT index)
{
if (m_deviceNotify)
{
m_deviceNotify->OnDeviceLost();
}
m_d3dDepthStencilView[index].Reset();
m_d3dRenderTargetView[index].Reset();
m_renderTargetTexture[index].Reset();
m_depthStencilTexture[index].Reset();
m_swapChain[index].Reset();
m_d3dContext.Reset();
m_d3dDevice.Reset();
m_dxgiFactory.Reset();
CreateDeviceResources();
CreateWindowSizeDependentResources(index);
if (m_deviceNotify)
{
m_deviceNotify->OnDeviceRestored();
}
}
int DeviceResources::getNumberOfMonitors()
{
ComPtr<IDXGIAdapter1> adapter;
GetHardwareAdapter(adapter.GetAddressOf());
IDXGIOutput* output = NULL;
int count = 0;
for (int i = 0; DXGI_ERROR_NOT_FOUND != adapter->EnumOutputs(i, &output); ++i)
{
count++;
}
return count;
}
RECTxywh DeviceResources::getMonitorSize(int monitor)
{
RECT position = getMonitorPos(monitor);
RECTxywh size(0, 0, position.right - position.left, position.bottom - position.top);
return size;
}
// 1 based index into monitors
RECT DeviceResources::getMonitorPos(int monitor)
{
ComPtr<IDXGIAdapter1> adapter;
GetHardwareAdapter(adapter.GetAddressOf());
RECT pos = {};
IDXGIOutput* output = NULL;
int count = -1;
if ( DXGI_ERROR_NOT_FOUND != adapter->EnumOutputs(monitor, &output) )
{
DXGI_OUTPUT_DESC outputDesc;
HRESULT hr = output->GetDesc(&outputDesc);
pos = outputDesc.DesktopCoordinates;
}
return pos;
}
RECT DeviceResources::getWindowPos(int index)
{
RECT windowRect;
HWND window = m_window[index];
GetWindowRect(window, &windowRect);
return windowRect;
}
void DeviceResources::setWindowPosition(int index, RECTxywh pos)
{
HWND hWnd = m_window[index];
SetWindowPos(hWnd, HWND_TOP, pos.left, pos.top, pos.width, pos.height, SWP_FRAMECHANGED)
ShowWindow(hWnd, SW_SHOWNORMAL)
}
bool DeviceResources::isWindowMinimized(int index)
{
return IsIconic(m_window[index]);
}
// Present the contents of the swap chain to the screen.
void DeviceResources::Present(int index)
{
HRESULT hr = E_FAIL;
if (m_options & c_AllowTearing)
{
hr = m_swapChain[index]->Present(0, DXGI_PRESENT_ALLOW_TEARING);
Print(L"TRACE: Present Present %i \n", index);
}
else
{
hr = m_swapChain[index]->Present(1, 0);
}
m_d3dContext->DiscardView(m_d3dRenderTargetView[index].Get());
if (m_d3dDepthStencilView[index])
{
// Discard the contents of the depth stencil.
m_d3dContext->DiscardView(m_d3dDepthStencilView[index].Get());
}
if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
{
HandleDeviceLost(index);
}
else
{
ThrowIfFailed(hr);
if (!m_dxgiFactory->IsCurrent())
{
CreateFactory();
}
}
}
void DeviceResources::CreateFactory()
{
ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(m_dxgiFactory.ReleaseAndGetAddressOf())));
}
void DeviceResources::GetHardwareAdapter(IDXGIAdapter1** ppAdapter)
{
...
}

Safe cancelling of CopyFileEx process

I've created a dialogbox with progress bar and a cancel button using CreateDialogParam to show status while copying several files (using CopyFileEx).
How do I cancel the process using CopyFileEx correctly, starting from pressing the cancel button in dialogbox? Is there anyway I can do it without using global variable? And How do I correctly handle the returned PROGRESS_CANCEL? I have provided questions in the code below to make clearer what help do I need.
//copy function
BOOL copy(HWND &hWnd, std::vector <FILECONSOLIDATEPARAMS> &vec)
{
//pass vector as lparam to dialogbox proc
LPARAM lp = reinterpret_cast<LPARAM>(&vec);
HWND hCopy = CreateDialogParam(GetModuleHandle(NULL),
MAKEINTRESOURCE(IDD_DIALOG1),
hwndmain, (DLGPROC)dlgboxcopyproc, lp);
static HWND hIDC_STATIC, hIDC_STATIC4;
hIDC_STATIC = GetDlgItem(hCopy, IDC_STATIC);
hIDC_STATIC4 = GetDlgItem(hCopy, IDC_STATIC4);
LPBOOL pbCancel = FALSE;
size_t s;
for (s = 0; s != vec.size(); s++)
{
SendMessage(hIDC_STATIC, WM_SETTEXT, 0, (LPARAM)vec[s].filename);
SendMessage(hIDC_STATIC4, WM_SETTEXT, 0,(LPARAM)vec[s].destination);
BOOL b = CopyFileEx(vec[s].filename, vec[s].destination,
&CopyProgressRoutine,(LPVOID)hCopy,pbCancel, NULL);
//how to catch and process PROGRESS_CANCEL?
if (!b)
{
DWORD dw = GetLastError();
ShowErrMsg(dw);
}
}
PostMessage(hCopy, WM_DESTROY, 0, 0);
return TRUE;
}
//dialogbox procedure
INT_PTR CALLBACK dlgboxcopyproc(HWND hWndDlg,UINT Msg,WPARAM wParam,LPARAM
lParam)
{
//translate passed lparam back to vector
std::vector<FILECONSOLIDATEPARAMS>& vect =
*reinterpret_cast<std::vector<FILECONSOLIDATEPARAMS>*>(lParam);
INITCOMMONCONTROLSEX _icex;
_icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
_icex.dwICC = ICC_PROGRESS_CLASS;
InitCommonControlsEx(&_icex);
static HWND hParent;
static HWND hIDCancel;
static HWND hIDC_PROGRESS1;
static HWND hIDC_STATIC;
hParent = GetParent(hWndDlg);
hIDCancel = GetDlgItem(hWndDlg, IDCANCEL);
hIDC_PROGRESS1 = GetDlgItem(hWndDlg, IDC_PROGRESS1);
switch (Msg)
{
case WM_INITDIALOG:
{
SendMessage(hIDC_PROGRESS1, PBM_SETRANGE, 0, MAKELPARAM(0, 100));
}
return (INT_PTR)TRUE;
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case IDCANCEL:
EndDialog(hWndDlg, FALSE); //how to make pbCancel = TRUE?
return (INT_PTR)TRUE;
}
}
break;
case WM_DESTROY:
{
DestroyWindow(hWndDlg);
}
}
return FALSE;
}
//copyprogressroutine callback function
DWORD CALLBACK CopyProgressRoutine(LARGE_INTEGER TotalFileSize,
LARGE_INTEGER TotalBytesTransferred, LARGE_INTEGER StreamSize,
LARGE_INTEGER StreamBytesTransferred, DWORD dwStreamNumber, DWORD
dwCallbackReason, HANDLE hSourceFile, HANDLE hDestinationFile, LPVOID
lpData)
{
HWND hWndDlg = (HWND)lpData;
static HWND hwndIDC_PROGRESS1;
hwndIDC_PROGRESS1 = GetDlgItem(hWndDlg, IDC_PROGRESS1);
DOUBLE Percentage = ((DOUBLE)TotalBytesTransferred.QuadPart /
(DOUBLE)TotalFileSize.QuadPart) * 100;
switch (dwCallbackReason)
{
case CALLBACK_CHUNK_FINISHED:
SendMessage(hwndIDC_PROGRESS1, PBM_SETPOS, (WPARAM) Percentage, 0);
break;
case CALLBACK_STREAM_SWITCH:
Percentage = 0;
break;
}
return PROGRESS_CONTINUE; //how to make conditional return PROGRESS_CANCEL?
}
code like
LPBOOL pbCancel = FALSE;
CopyFileEx(, pbCancel, )
senseless. really we simply pass 0 in place pbCancel and have no ability cancel operation.
we need alocate some variable (let name it bCancel) of type BOOL and pass pointer of this variable to CopyFileEx
something like this:
BOOL bCancel = FALSE;
CopyFileEx(, &bCancel, )
the CopyFileEx will be periodically query value of this variable by passed pointer and if it became true - break operation and return ERROR_REQUEST_ABORTED error.
the next - CopyFileEx not return until operation is complete - this is synchronous api - as result it can not be called from GUI thread (or it simply block GUI). need call it from separate thread.
so basic solution - allocate some data structure, here place BOOL bCancel, and other data, which we will be use during copy. we will access this data structure from 2 threads - gui thread (from dialog procedure) and from separate thread, which will call CopyFileEx. for correct implement this - need use reference counting on structure. the lpProgressRoutine need post messages to gui thread for notify it about progress (gui thread can move progress bars on this notification). dialog can containing for example Cancel button. when user click it - GUI thread simply set bCancel = TRUE, as result CopyFileEx abort operation on next chunk. for start copy - need start new thread, which call CopyFileEx. based on required logic - can do this from WM_INITDIALOG or say when user press some button in dialog
basic code:
struct CopyDlg
{
enum {
WM_COPYRESULT = WM_APP, WM_PROGRESS
};
struct ProgressData {
LARGE_INTEGER TotalFileSize;
LARGE_INTEGER TotalBytesTransferred;
LARGE_INTEGER StreamSize;
LARGE_INTEGER StreamBytesTransferred;
DWORD dwStreamNumber;
};
PCWSTR m_lpExistingFileName, m_lpNewFileName;
HWND m_hwnd, m_hwndFile, m_hwndStream;
ULONG m_shift;
LONG m_dwRefCount;
LONG m_hwndLock;
BOOL m_bCancel;
CopyDlg()
{
m_dwRefCount = 1;
}
void AddRef()
{
InterlockedIncrement(&m_dwRefCount);
}
void Release()
{
if (!InterlockedDecrement(&m_dwRefCount))
{
delete this;
}
}
void LockWnd()
{
InterlockedIncrement(&m_hwndLock);
}
void UnlockWnd()
{
if (!InterlockedDecrement(&m_hwndLock))
{
// want m_hwnd be valid at PostMessage(p->m_hwnd,) time
EndDialog(m_hwnd, 0);
}
}
void OnProgress(DWORD dwCallbackReason, ProgressData* p)
{
if (dwCallbackReason == CALLBACK_STREAM_SWITCH)
{
if (p->dwStreamNumber == 1)
{
m_shift = 0;
LONGLONG QuadPart = p->TotalFileSize.QuadPart;
while (QuadPart > MAXLONG)
{
m_shift++;
QuadPart >>= 1;
}
SendMessage(m_hwndFile, PBM_SETRANGE32, 0, (LPARAM)QuadPart);
SendMessage(m_hwndFile, PBM_SETPOS, 0, 0);
}
SendMessage(m_hwndStream, PBM_SETRANGE32, 0, (LPARAM)(p->StreamSize.QuadPart >> m_shift));
SendMessage(m_hwndStream, PBM_SETPOS, 0, 0);
}
else
{
SendMessage(m_hwndStream, PBM_SETPOS, (LPARAM)(p->StreamBytesTransferred.QuadPart >> m_shift), 0);
SendMessage(m_hwndFile, PBM_SETPOS, (LPARAM)(p->TotalBytesTransferred.QuadPart >> m_shift), 0);
}
}
ULONG StartCopy(PCWSTR lpExistingFileName, PCWSTR lpNewFileName)
{
m_bCancel = FALSE;
m_lpExistingFileName = lpExistingFileName;
m_lpNewFileName = lpNewFileName;
LockWnd();
AddRef();
if (HANDLE hThread = CreateThread(0, 0, reinterpret_cast<PTHREAD_START_ROUTINE>(CopyThread), this, 0, 0))
{
CloseHandle(hThread);
return NOERROR;
}
Release();
UnlockWnd();
return GetLastError();
}
static INT_PTR CALLBACK _DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
if (uMsg == WM_INITDIALOG)
{
SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR)lParam);
}
if (CopyDlg* p = reinterpret_cast<CopyDlg*>(GetWindowLongPtrW(hwndDlg, DWLP_USER)))
{
p->AddRef();
INT_PTR r = p->DialogProc(hwndDlg, uMsg, wParam, lParam);
p->Release();
return r;
}
return 0;
}
INT_PTR DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_NCDESTROY:
Release();
break;
case WM_DESTROY:
m_bCancel = TRUE;
break;
case WM_COMMAND:
switch (wParam)
{
case MAKEWPARAM(IDCANCEL, BN_CLICKED):
m_bCancel = TRUE;
break;
}
break;
case WM_CLOSE:
m_bCancel = TRUE;
UnlockWnd();
ShowWindow(hwndDlg, SW_HIDE);//for not get wm_close twice
break;
case WM_COPYRESULT:
UnlockWnd();
// lParam == error code from CopyFileExW
DbgPrint("CopyFileExW=%u\n", (ULONG)lParam);
break;
case WM_PROGRESS:
OnProgress((DWORD)wParam, reinterpret_cast<ProgressData*>(lParam));
delete (void*)lParam;
break;
case WM_INITDIALOG:
AddRef();
m_hwnd = hwndDlg;
m_hwndStream = GetDlgItem(hwndDlg, IDC_PROGRESS1);
m_hwndFile = GetDlgItem(hwndDlg, IDC_PROGRESS2);
m_hwndLock = 1;
StartCopy(L"**", L"**");
break;
}
return 0;
}
static ULONG CALLBACK CopyThread(CopyDlg* p)
{
PostMessage(p->m_hwnd, WM_COPYRESULT, 0, CopyFileExW(
p->m_lpExistingFileName, p->m_lpNewFileName,
reinterpret_cast<LPPROGRESS_ROUTINE>(CopyProgressRoutine),
p, &p->m_bCancel, 0) ? NOERROR : GetLastError());
p->Release();
return 0;
}
static DWORD CALLBACK CopyProgressRoutine(
__in LARGE_INTEGER TotalFileSize,
__in LARGE_INTEGER TotalBytesTransferred,
__in LARGE_INTEGER StreamSize,
__in LARGE_INTEGER StreamBytesTransferred,
__in DWORD dwStreamNumber,
__in DWORD dwCallbackReason,
__in HANDLE /*hSourceFile*/,
__in HANDLE /*hDestinationFile*/,
__in_opt CopyDlg* p
)
{
switch(dwCallbackReason)
{
case CALLBACK_CHUNK_FINISHED:
case CALLBACK_STREAM_SWITCH:
if (ProgressData* data = new ProgressData)
{
data->TotalFileSize = TotalFileSize;
data->TotalBytesTransferred = TotalBytesTransferred;
data->StreamSize = StreamSize;
data->StreamBytesTransferred = StreamBytesTransferred;
data->dwStreamNumber = dwStreamNumber;
if (!PostMessage(p->m_hwnd, WM_PROGRESS, dwCallbackReason, (LPARAM)data))
{
delete data;
return PROGRESS_CANCEL;
}
}
break;
}
// for debugging
//Sleep(3000);
//MessageBoxW(0,0,0,0);
return PROGRESS_CONTINUE;
}
};
if (CopyDlg* p = new CopyDlg)
{
DialogBoxParamW((HINSTANCE)&__ImageBase, MAKEINTRESOURCE(IDD_DIALOG1), HWND_DESKTOP, CopyDlg::_DialogProc, (LPARAM)p);
p->Release();
}

Change the color of the title bar (caption) of a win32 application

I want to change the color of the title bar in my application as I have seen done in programs such as Skype Preview. I have found only one solution offered on the internet for this (WM_NCPAINT) which seems to require me to draw a completely custom title bar which is of course not ideal when all I want to do is change the background color. Is anyone aware of a better solution? Someone suggested hooking GetSysColor, but it is never called with an index of 2 (COLOR_ACTIVECAPTION) so the color is being retrieved from elsewhere.
Current title bar:
(source: pbrd.co)
End goal:
You can change window title bar color / behaviour with DWMAPI's DwmSetWindowAttribute function in Win32.
NOTE: Might require Windows SDK 10.0.22000.0 (aka first Windows 11 SDK) as DWMWA_USE_IMMERSIVE_DARK_MODE|DWMWA_BORDER_COLOR|DWMWA_CAPTION_COLOR were not documented in Windows SDK 10.0.19041.0 (latest Windows 10 SDK). People have got DWMWA_USE_IMMERSIVE_DARK_MODE working before the public documentation of the variable by simply using dwAttribute as 20 (or 19 if Windows was before Windows 10 20H1). Here is an example of Qt using it in their Windows platform integration by allowing application to use it by passing -platform windows:darkmode=1 flag when launching the application.
To enable immersive dark mode (available in Windows 10 / 11, but undocumented in Windows 10 SDK (can be used by setting value as dwAttribute as 20), value was 19 pre Windows 10 20H1 Update)
Immersive Dark Mode Enabled
Immersive Dark Mode Enabled Out of Focus
#include <dwmapi.h>
BOOL USE_DARK_MODE = true;
BOOL SET_IMMERSIVE_DARK_MODE_SUCCESS = SUCCEEDED(DwmSetWindowAttribute(
WINhWnd, DWMWINDOWATTRIBUTE::DWMWA_USE_IMMERSIVE_DARK_MODE,
&USE_DARK_MODE, sizeof(USE_DARK_MODE)));
To change border color (only in Windows 11 SDK)
Border Color set to 0x00FFFFFF
Border Color set to 0x00505050
#include <dwmapi.h>
COLORREF DARK_COLOR = 0x00505050;
BOOL SET_CAPTION_COLOR = SUCCEEDED(DwmSetWindowAttribute(
WINhWnd, DWMWINDOWATTRIBUTE::DWMWA_BORDER_COLOR,
&DARK_COLOR, sizeof(DARK_COLOR)));
To change caption color (only in Windows 11 SDK)
Caption Color set to 0x00FFFFFF
Caption Color set to 0x00505050
#include <dwmapi.h>
COLORREF DARK_COLOR = 0x00505050;
BOOL SET_CAPTION_COLOR = SUCCEEDED(DwmSetWindowAttribute(
WINhWnd, DWMWINDOWATTRIBUTE::DWMWA_CAPTION_COLOR,
&DARK_COLOR, sizeof(DARK_COLOR)));
The first thing I'm going to say is: You have been warned!
This is an awfully laborious task. It's a long way from easy and much time was spent reading the Wine sources (linux implementation of native win32 functionality)
Seeing this question brought back 'fond' (read: exasperating!) memories of my efforts to achieve the same result. The process is a somewhat convoluted one and foisters upon you a great many more responsibilities than simply painting the title-bar. (I've included about 500 lines of code)
Amongst other things, you need to handle window activation/inactivation, sizing, NC area buttons, application icon and title-text.
Using some (drawing) utility functions in other files I've not included, the following was achieved:
Both of which are modifications to this dialog:
With the assistance of these (color-keyed) images:
and some stretching/drawing (the image is divided into 9 pieces)
I note upon re-vising this code, that the borders are over-drawn by the client-area. I imagine, because I've not sized it correctly in response to the WM_NCCALCSIZE message. I also used another image which did indeed have borders of 8pixels wide, rather than the 14 that these two show. (You can see the commented-out code in response to the message I mentioned)
The idea is that first, we sub-class the standard dialog-box's WindowProc. In this subclassed handler, we tell the Desktop Window Manager to disable composition for our window, we setup a layered window (this is how the black one appears semi-transparent) and then finally, do the non-client drawing ourselves in response to a WM_NCPAINT message.
I'll also point out that for reasons that have long since escaped me, I wasn't especially satisfied with the functioning of the code.
With that said, here's some code to sink your teeth into:
#define _WIN32_WINNT 0x0501
#define UNICODE 1
#include <windows.h>
#include <commctrl.h>
#include <stdio.h>
#include "resource.h"
#include "../graphics/graphics.h"
#include <dwmapi.h>
using namespace Gdiplus;
HINSTANCE hInst;
LRESULT CALLBACK DlgSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData);
LRESULT onNcPaint(HWND hwnd, WPARAM wParam, LPARAM lParam);
HBITMAP frameImg, frameRedImg, frameOrigImg;
int frameIndex = 0;
//HRESULT DwmEnableComposition(UINT uCompositionAction);
typedef HRESULT (WINAPI *pFnDwmEnableComposition)(UINT uCompAction);
typedef HRESULT (WINAPI *pFnDwmSetWindowAttribute)(HWND hwnd, DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute);
#define WM_DMWNCRENDERINGCHANGED 0x31F
// wParam = 1 (fRenderingEnabled = true)
// wParam = 0 (fRenderingEnabled = false)
HRESULT EnableNcDwm(HWND hwnd, bool enable)
{
HMODULE dwmMod = LoadLibrary(L"dwmapi.dll");
if (dwmMod)
{
pFnDwmSetWindowAttribute DwmSetWindowAttribute;
DwmSetWindowAttribute = (pFnDwmSetWindowAttribute)GetProcAddress(dwmMod, "DwmSetWindowAttribute");
HRESULT hr = S_OK;
DWMNCRENDERINGPOLICY ncrp;
if (enable)
ncrp = DWMNCRP_ENABLED;
else
ncrp = DWMNCRP_DISABLED;
// Disable non-client area rendering on the window.
hr = DwmSetWindowAttribute(hwnd, DWMWA_NCRENDERING_POLICY, &ncrp, sizeof(ncrp));
FreeLibrary(dwmMod);
if (SUCCEEDED(hr))
{
return hr;
}
}
return S_FALSE;
}
/*
#define DWM_EC_DISABLECOMPOSITION 0
#define DWM_EC_ENABLECOMPOSITION 1
HRESULT EnableDWM(HWND hwnd, bool enable)
{
HMODULE dwmMod = LoadLibrary(L"dwmapi.dll");
pFnDwmEnableComposition DwmEnableComposition;
DwmEnableComposition = (pFnDwmEnableComposition)GetProcAddress(dwmMod, "DwmEnableComposition");
HRESULT hr = S_OK;
// Disable DWM Composition
if (enable)
hr = DwmEnableComposition(DWM_EC_ENABLECOMPOSITION);
else
hr = DwmEnableComposition(DWM_EC_DISABLECOMPOSITION);
FreeLibrary(dwmMod);
return hr;
}
*/
BOOL CALLBACK DlgMain(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static bool isSubclassed = false;
switch(uMsg)
{
case WM_DMWNCRENDERINGCHANGED:
{
long dwEx = GetWindowLong(hwndDlg, GWL_EXSTYLE);
dwEx &= ~(WS_EX_LAYERED);
SetWindowLong(hwndDlg, GWL_EXSTYLE, dwEx);
InvalidateRect(hwndDlg, NULL, true);
UpdateWindow(hwndDlg);
MoveAnchorsImmediatelly(hwndDlg);
}
return 0;
// case WM_ERASEBKGND:
// {
// RECT rc;
// GetClientRect(hwndDlg, &rc);
// FillRect((HDC)wParam, &rc, (HBRUSH) COLOR_BACKGROUND);
// return 1;
// }
case WM_INITDIALOG:
{
mSetAnchorMode(GetDlgItem(hwndDlg, IDC_BUTTON1), ANCHOR_CENTER);
}
return TRUE;
case WM_SIZE:
{
//MoveAnchorsImmediatelly(hwndDlg);
DeferAnchorsMove(hwndDlg);
}
return TRUE;
case WM_CLOSE:
{
EndDialog(hwndDlg, 0);
}
return TRUE;
case WM_COMMAND:
{
switch(LOWORD(wParam))
{
case IDC_BUTTON1:
if (isSubclassed == false)
{
SetWindowSubclass( hwndDlg, DlgSubclassProc, 1, NULL);
EnableNcDwm(hwndDlg, false);
frameIndex++;
frameIndex &= 1; // make sure it can only be in range [0..1]
}
else
{
RemoveWindowSubclass( hwndDlg, DlgSubclassProc, 1);
EnableNcDwm(hwndDlg, true);
}
isSubclassed = !isSubclassed;
// InvalidateRect(hwndDlg, NULL, true);
// UpdateWindow(hwndDlg);
// MoveAnchorsImmediatelly(hwndDlg);
break;
}
}
return TRUE;
}
return FALSE;
}
LRESULT CALLBACK DlgSubclassProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
static byte alpha = 255;
switch (uMsg)
{
case WM_ENTERSIZEMOVE:
printf("WM_ENTERSIZEMOVE\n");
return 0;
break;
case WM_EXITSIZEMOVE:
printf("WM_EXITSIZEMOVE\n");
return 0;
break;
case WM_MOUSEWHEEL:
if (((SHORT)(HIWORD(wParam))) > 0)
{
if (alpha > 30)
alpha -= 5;
}
else if (alpha < 255)
alpha += 5;
SetLayeredWindowAttributes(hwnd, RGB(255,0,255), alpha, LWA_COLORKEY|LWA_ALPHA);
UpdateWindow(hwnd);
return 0;
case WM_DMWNCRENDERINGCHANGED:
{
// printf("WM_DMWNCRENDERINGCHANGED\n");
long dwEx = GetWindowLong(hwnd, GWL_EXSTYLE);
dwEx |= WS_EX_LAYERED;
SetWindowLong(hwnd, GWL_EXSTYLE, dwEx);
SetLayeredWindowAttributes(hwnd, RGB(255,0,255), alpha, LWA_COLORKEY|LWA_ALPHA);
//MoveAnchorsImmediatelly(hwnd);
DeferAnchorsMove(hwnd);
InvalidateRect(hwnd, NULL, true);
UpdateWindow(hwnd);
// showWndRect(hwnd);
return 0;
}
break;
case WM_NCACTIVATE:
case WM_NCPAINT:
// printf("WM_NCPAINT -");
// printf("wParam: 0x%08d lParam 0x%08x\n", wParam, lParam);
onNcPaint(hwnd, wParam, lParam);
return 0;
case WM_NCCALCSIZE:
{
RECT *rc = (RECT*)lParam;
rc->left += 8; // frame image margin widths
rc->top += 30;
rc->right -= 8;
rc->bottom -= 8;
// rc->left += 14; // frame image margin widths
// rc->top += 39;
// rc->right -= 14;
// rc->bottom -= 14;
}
return (WVR_HREDRAW | WVR_VREDRAW);
case WM_NCHITTEST:
{
POINT mousePos, rawMousePos;
RECT clientRect, windowRect;
mousePos.x = LOWORD(lParam);
mousePos.y = HIWORD(lParam);
rawMousePos = mousePos;
GetClientRect(hwnd, &clientRect);
GetWindowRect(hwnd, &windowRect);
ScreenToClient(hwnd, &mousePos);
if ((mousePos.x < clientRect.left) && (rawMousePos.y < windowRect.top+8))
return HTTOPLEFT;
if ((mousePos.x > clientRect.right) && (rawMousePos.y < windowRect.top+8))
return HTTOPRIGHT;
if ( (mousePos.x < clientRect.left) && (mousePos.y > clientRect.bottom))
return HTBOTTOMLEFT;
if ( (mousePos.x > clientRect.right) && (mousePos.y > clientRect.bottom))
return HTBOTTOMRIGHT;
if (rawMousePos.x < windowRect.left+11)
return HTLEFT;
if (rawMousePos.x > windowRect.right-11)
return HTRIGHT;
if (mousePos.y > clientRect.bottom)
return HTBOTTOM;
RECT closeRect;
SetRect(&closeRect, windowRect.left + 15, windowRect.top+7, windowRect.left+15+16, windowRect.top+25);
if (PtInRect(&closeRect, rawMousePos))
{
// printf("over sys menu (appIcon) - %d,%d\n", mousePos.x, mousePos.y);
return HTSYSMENU;
}
if (rawMousePos.y < windowRect.top+8)
return HTTOP;
if (mousePos.y < 0)
return HTCAPTION;
else
return HTCLIENT;
}
}
return DefSubclassProc(hwnd, uMsg, wParam, lParam);
// return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
LRESULT onNcPaint(HWND hwnd, WPARAM wParam, LPARAM lParam)
{
// draw Frame
// HBRUSH mBrush = CreateSolidBrush( RGB(0,113,201) );
HDC hdc = GetWindowDC(hwnd);
// HDC hdc = GetDCEx(hwnd, (HRGN)wParam, DCX_WINDOW);//|DCX_INTERSECTRGN);
RECT mRect, wndRect;
GetWindowRect(hwnd, &mRect);
wndRect = mRect;
mRect.right -= mRect.left;
mRect.bottom -= mRect.top;
mRect.left = 0;
mRect.top = 0;
HDC memDC = CreateCompatibleDC(hdc);
HBITMAP old, memBmp;
old = (HBITMAP)GetCurrentObject(memDC, OBJ_BITMAP);
memBmp = CreateCompatibleBitmap(hdc, mRect.right, mRect.bottom);
//memBmp = zCreateDibSection(hdc, mRect.right, mRect.bottom, 24);
SelectObject(memDC, memBmp);
//StretchNineDraw(HDC destDC, RECT destRect, HBITMAP srcImage, RECT srcRect,
// int marginLeft, int marginTop, int marginRight, int marginBottom, int alpha);
if (frameIndex == 0)
// StretchNineDraw(memDC, mRect, frameImg, (RECT){0,0,33,58}, 16,41,16,16, 255);
StretchNineDrawNoAlpha(memDC, mRect, frameImg, (RECT){0,0,33,58}, 16,41,16,16);
else
StretchNineDraw(memDC, mRect, frameRedImg, (RECT){0,0,33,58}, 16,41,16,16, 255);
// StretchNineDrawNoAlpha(memDC, mRect, frameRedImg, (RECT){0,0,33,58}, 16,41,16,16);
// StretchNineDrawNoAlpha(memDC, mRect, frameOrigImg, (RECT){0,0,17,39}, 8,30,8,8);
//1111drawImgNineSquareStretching(memDC, mRect, frameImg, (RECT){0,0,33,58}, 16,41,16,16);
//void StretchNineDrawNoAlpha(HDC destDC, RECT destRect, HBITMAP srcImage, RECT srcRect,
// int marginLeft, int marginTop, int marginRight, int marginBottom)
// draw icon
HICON smallIcon = LoadIcon (NULL, IDI_APPLICATION);
DrawIconEx(memDC, 15, 9, smallIcon, 16, 16, 0,0, DI_NORMAL );
// draw window text
wchar_t wndText[100];
RECT textRect;
textRect.left = 9 + 16 + 9;
textRect.top = 0;
textRect.right = 1000;
textRect.bottom = 32;
GetWindowText(hwnd, wndText, 99);
//int oldMode = SetBkMode(hdc, TRANSPARENT);
//int oldMode = SetBkMode(memDC, TRANSPARENT);
SetBkMode(memDC, TRANSPARENT);
HFONT oldFont, hfont0 = CreateFont(-13, 0, 0, 0, 0, FALSE, FALSE, FALSE, 1, 0, 0, 0, 0, (L"Ms Shell Dlg"));
oldFont = (HFONT)SelectObject(memDC, hfont0);
DrawText(memDC, wndText, -1, &textRect, DT_VCENTER|DT_SINGLELINE|DT_LEFT);
SelectObject(memDC, oldFont);
DeleteObject(hfont0);
// top slice
BitBlt(hdc, 0,0, mRect.right,41, memDC, 0,0, SRCCOPY);
// left edge
BitBlt(hdc, 0, mRect.top + 41, 16, mRect.bottom - (41+16),
memDC, 0, mRect.top + 41, SRCCOPY);
// right edge
BitBlt(hdc, mRect.right-16, mRect.top + 41, 16, mRect.bottom - (41+16),
memDC, mRect.right-16, mRect.top + 41, SRCCOPY);
// bottom slice
BitBlt(hdc, 0,mRect.bottom-16, mRect.right,16, memDC, 0,mRect.bottom-16, SRCCOPY);
// BitBlt(hdc, 0,0, mRect.right,mRect.bottom, memDC, 0,0, SRCCOPY);
ReleaseDC(hwnd, hdc);
SelectObject(memDC, old);
DeleteDC(memDC);
DeleteObject(memBmp);
// ValidateRgn(hwnd, (HRGN)wParam);
return 0;
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
frameImg = mLoadImageFile(L"frame.png");
frameRedImg = mLoadImageFile(L"frameRed.png");
frameOrigImg = mLoadImageFile(L"frameOrig.png");
hInst=hInstance;
InitCommonControls();
int result = DialogBox(hInst, MAKEINTRESOURCE(DLG_MAIN), NULL, (DLGPROC)DlgMain);
GdiplusShutdown(gdiplusToken);
return result;
}
Find below the functions that:
- Load a png file (uses GDI+)
- stretch draw this image onto the borders
/* BMP, GIF, JPEG, PNG, TIFF, Exif, WMF, and EMF */
HBITMAP mLoadImageFile(wchar_t *filename)
{
HBITMAP result = NULL;
Bitmap bitmap(filename, false);
bitmap.GetHBITMAP(0, &result);
return result;
}
void GetRectSize(LPRECT tgt, int *width, int *height)
{
*width = (tgt->right - tgt->left) + 1;
*height = (tgt->bottom - tgt->top) + 1;
}
BOOL SetRectSizePos(LPRECT tgt, int xPos, int yPos, int width, int height)
{
return SetRect(tgt, xPos, yPos, xPos+(width-1), yPos+(height-1));
}
BOOL MoveRect(LPRECT tgt, int newX, int newY)
{
int width, height;
GetRectSize(tgt, &width, &height);
return SetRectSizePos(tgt, newX,newY, width,height);
}
// ****** marginLeft = 6
// ....|....|.... *
// ..tL.|.tM.|.tR.. *
// ---------------- * marginTop = 3
// ..mL.|.mM.|.mR..
// ---------------- * marginBottom = 3
// ..bL.|.bM.|.bR.. *
// ....|....|.... *
// ****** marginRight = 6
void CalcNineRects(LPRECT srcRect, RECT *dest, int marginLeft, int marginTop, int marginRight, int marginBottom)
{
int srcWidth, srcHeight;
int leftWidth, midWidth, rightWidth;
int topHeight, midHeight, botHeight;
int xOrig, yOrig;
GetRectSize(srcRect, &srcWidth, &srcHeight);
xOrig = srcRect->left;
yOrig = srcRect->top;
leftWidth = marginLeft;
midWidth = srcWidth - (marginLeft + marginRight) - 1;
rightWidth = marginRight;
topHeight = marginTop;
midHeight = srcHeight - (marginTop + marginBottom) - 1;
botHeight = marginBottom;
SetRectSizePos(&dest[0], xOrig, yOrig, leftWidth, topHeight);
SetRectSizePos(&dest[1], xOrig+(leftWidth), yOrig, midWidth, topHeight);
SetRectSizePos(&dest[2], xOrig+(leftWidth+midWidth), yOrig, rightWidth, topHeight);
SetRectSizePos(&dest[3], xOrig, yOrig+(topHeight), leftWidth, midHeight);
SetRectSizePos(&dest[4], xOrig+(leftWidth), yOrig+(topHeight), midWidth, midHeight);
SetRectSizePos(&dest[5], xOrig+(leftWidth+midWidth), yOrig+(topHeight), rightWidth, midHeight);
SetRectSizePos(&dest[6], xOrig,yOrig+(topHeight+midHeight), leftWidth, botHeight);
SetRectSizePos(&dest[7], xOrig+(leftWidth), yOrig+(topHeight+midHeight), midWidth, botHeight);
SetRectSizePos(&dest[8], xOrig+(leftWidth+midWidth), yOrig+(topHeight+midHeight), rightWidth, botHeight);
}
void StretchNineDraw(HDC destDC, RECT destRect, HBITMAP srcImage, RECT srcRect,
int marginLeft, int marginTop, int marginRight, int marginBottom,int alpha)
{
RECT destRectList[9], srcRectList[9];
int i;
int curSrcWidth, curSrcHeight, curDestWidth, curDestHeight;
HDC srcDC;
HBITMAP oldSrcBmp;
srcDC = CreateCompatibleDC(destDC);
// GetCurrentObject(srcDC, OBJ_BITMAP);
oldSrcBmp = (HBITMAP) SelectObject(srcDC, srcImage);
BLENDFUNCTION bf = {AC_SRC_OVER,0,alpha,AC_SRC_ALPHA};
int destHeight, destWidth;
GetRectSize(&destRect, &destWidth, &destHeight);
CalcNineRects(&srcRect, srcRectList, marginLeft, marginTop, marginRight, marginBottom);
CalcNineRects(&destRect, destRectList, marginLeft, marginTop, marginRight, marginBottom);
// printf("dst rect: %d,%d - %d,%d -- \n", destRect.left, destRect.top, destRect.right,destRect.bottom);
for (i=0; i<9; i++)
{
GetRectSize(&srcRectList[i], &curSrcWidth, &curSrcHeight);
GetRectSize(&destRectList[i], &curDestWidth, &curDestHeight);
AlphaBlend( destDC,
destRectList[i].left, destRectList[i].top,
curDestWidth, curDestHeight,
srcDC,
srcRectList[i].left, srcRectList[i].top,
curSrcWidth, curSrcHeight,
bf
);
}
SelectObject(srcDC, oldSrcBmp);
DeleteDC(srcDC);
}
Finally, the code for anchoring controls to the window (automatically recalculate their position when the window is re-sized)
typedef struct ANCHORPROPERTY
{
long anchorType;
RECT rc;
} *pANCHORPROPERTY;
#define ANCHOR_NONE 0
#define ANCHOR_WIDTH 1
#define ANCHOR_RIGHT 2
#define ANCHOR_CENTER_HORZ 3
#define ANCHOR_HEIGHT 4
#define ANCHOR_HEIGHT_WIDTH 5
#define ANCHOR_HEIGHT_RIGHT 6
#define ANCHOR_BOTTOM 7
#define ANCHOR_BOTTOM_WIDTH 8
#define ANCHOR_BOTTOM_RIGHT 9
#define ANCHOR_CENTER_HORZ_BOTTOM 10
#define ANCHOR_CENTER_VERT 11
#define ANCHOR_CENTER_VERT_RIGHT 12
#define ANCHOR_CENTER 13
pANCHORPROPERTY getWndAnchor(HWND hwnd);
bool removeAnchor(HWND hwnd);
bool mSetAnchorMode(HWND hwnd, long anchorMode);
BOOL CALLBACK AnchorEnum(HWND hwnd, LPARAM lParam);
void MoveAnchorsImmediatelly(HWND controlParent);
void DeferAnchorsMove(HWND controlParent);
long getChildCount(HWND controlParent);
pANCHORPROPERTY getWndAnchor(HWND hwnd)
{
return (pANCHORPROPERTY)GetProp(hwnd, L"anchor");
}
bool removeAnchor(HWND hwnd)
{
pANCHORPROPERTY pAnchor;
if (GetProp(hwnd, L"anchor") != NULL)
{
pAnchor = (pANCHORPROPERTY)RemoveProp(hwnd, L"anchor");
delete pAnchor;
}
return false;
}
bool mSetAnchorMode(HWND hwnd, long anchorMode)
{
bool result = false;
RECT rc, pr;
POINT p;
if (IsWindow(hwnd))
{
pANCHORPROPERTY pAnchor;
pAnchor = getWndAnchor(hwnd);
if (pAnchor == NULL)
{
pAnchor = new ANCHORPROPERTY;
SetProp(hwnd, L"anchor", pAnchor);
}
GetWindowRect(hwnd, &rc);
p.x = rc.left;
p.y = rc.top;
ScreenToClient( GetParent(hwnd), &p);
GetClientRect( GetParent(hwnd), &pr);
// printf("pos: %d,%d\n", p.x, p.y);
pAnchor->anchorType = mmin( mmax(anchorMode, ANCHOR_NONE), ANCHOR_CENTER);
pAnchor->rc.left = p.x;
pAnchor->rc.top = p.y;
pAnchor->rc.right = pr.right - (rc.right-rc.left + p.x);
pAnchor->rc.bottom = pr.bottom - (rc.bottom - rc.top + p.y);
result = true;
}
return result;
}
BOOL CALLBACK AnchorEnum(HWND hwnd, LPARAM lParam)
{
RECT pr, rc;
long x,y,xW,yH;
pANCHORPROPERTY pAnchor;
pAnchor = (pANCHORPROPERTY)GetProp(hwnd, L"anchor");
if (pAnchor != NULL)
{
if (pAnchor->anchorType != ANCHOR_NONE)
{
// printf("child enumerated - %d\n", pAnchor->anchorType);
RECT client, wnd;
GetClientRect(hwnd, &client);
GetWindowRect(hwnd, &wnd);
// printf("WndRect: %d x %d", (wnd.right-wnd.left) + 1, (wnd.bottom-wnd.top)+1);
// printf("client: %d x %d", client.right-client.left+1, client.bottom-client.top+1 );
int wW, wH, cW,cH;
wW = (wnd.right-wnd.left) + 1;
wH = (wnd.bottom-wnd.top) + 1;
cW = (client.right-client.left) + 1;
cH = (client.bottom-client.top) + 1;
GetClientRect(hwnd, &rc);
GetClientRect(GetParent(hwnd), &pr);
switch (pAnchor->anchorType)
{
case ANCHOR_WIDTH:
x = pAnchor->rc.left;
y = pAnchor->rc.top;
xW = mmax(pr.right - pAnchor->rc.left - pAnchor->rc.right, 0);
yH = rc.bottom;
break;
case ANCHOR_RIGHT: // = 2
x = (pr.right - rc.right - pAnchor->rc.right) - (wW-cW);
y = pAnchor->rc.top;
xW = rc.right + (wW-cW);
yH = rc.bottom + (wH-cH);
// printf("xPos, yPos: %d, %d - Size: %d x %d\n", x,y,xW,yH);
break;
case ANCHOR_CENTER_HORZ: // = 3
x = (pr.right - rc.right) / 2;
y = pAnchor->rc.top;
xW = rc.right;
yH = rc.bottom;
break;
case ANCHOR_HEIGHT: // = 4
x = pAnchor->rc.left;
y = pAnchor->rc.top;
xW = rc.right;
yH = mmax(pr.bottom - pAnchor->rc.top - pAnchor->rc.bottom, 0);
break;
case ANCHOR_HEIGHT_WIDTH: // = 5
x = pAnchor->rc.left;
y = pAnchor->rc.top;
xW = mmax(pr.right - pAnchor->rc.left - pAnchor->rc.right, 0);
yH = mmax(pr.bottom - pAnchor->rc.top - pAnchor->rc.bottom, 0);
break;
case ANCHOR_HEIGHT_RIGHT: // = 6
x = pr.right - rc.right - pAnchor->rc.right;
y = pAnchor->rc.top;
xW = rc.right;
yH = mmax(pr.bottom - pAnchor->rc.top - pAnchor->rc.bottom, 0);
break;
case ANCHOR_BOTTOM: // = 7
x = pAnchor->rc.left;
y = pr.bottom - pAnchor->rc.bottom - rc.bottom;
xW = rc.right;
yH = rc.bottom;
break;
case ANCHOR_BOTTOM_WIDTH: // = 8
x = pAnchor->rc.left;
y = pr.bottom - pAnchor->rc.bottom - rc.bottom;
xW = mmax(pr.right - pAnchor->rc.left - pAnchor->rc.right, 0);
yH = rc.bottom;
break;
case ANCHOR_BOTTOM_RIGHT: // = 9
x = pr.right - rc.right - pAnchor->rc.right;
y = pr.bottom - pAnchor->rc.bottom - rc.bottom;
xW = rc.right;
yH = rc.bottom;
break;
case ANCHOR_CENTER_HORZ_BOTTOM: // = 10
x = (pr.right - rc.right) / 2;
y = pr.bottom - pAnchor->rc.bottom - rc.bottom;
xW = rc.right;
yH = rc.bottom;
break;
case ANCHOR_CENTER_VERT: // = 11
x = pAnchor->rc.left;
y = (pr.bottom - rc.bottom) / 2;
xW = rc.right;
yH = rc.bottom;
break;
case ANCHOR_CENTER_VERT_RIGHT: // = 12
x = pr.right - rc.right - pAnchor->rc.right;
y = (pr.bottom - rc.bottom) / 2;
xW = rc.right;
yH = rc.bottom;
break;
case ANCHOR_CENTER: // = 13
x = (pr.right - rc.right) / 2;
y = (pr.bottom - rc.bottom) / 2;
xW = rc.right;
yH = rc.bottom;
break;
}
if (lParam == 0)
SetWindowPos(hwnd,0, x,y, xW,yH, SWP_NOZORDER|SWP_NOCOPYBITS);
else
DeferWindowPos((HDWP)lParam, hwnd, 0, x,y, xW,yH, SWP_NOZORDER|SWP_NOCOPYBITS);
}
}
return true;
}
void MoveAnchorsImmediatelly(HWND controlParent)
{
EnumChildWindows(controlParent, AnchorEnum, 0);
}
BOOL CALLBACK CountEnum(HWND hwnd, LPARAM lParam)
{
long *pCount = (long*)lParam;
++(*pCount);
return true;
}
long getChildCount(HWND controlParent)
{
long curCount = 0;
EnumChildWindows(controlParent, CountEnum, (LPARAM)&curCount);
// printf("Child count: %d\n", curCount);
return curCount;
}
void DeferAnchorsMove(HWND controlParent)
{
HDWP deferMoveHandle;
int childCount = getChildCount(controlParent);
deferMoveHandle = BeginDeferWindowPos(childCount);
EnumChildWindows(controlParent, AnchorEnum, (LPARAM)deferMoveHandle);
EndDeferWindowPos(deferMoveHandle);
}
You may try to create a window without a frame; i found reference here:
opening a window that has no title bar with win32
and then make your own title bar inside your application, in the color you like (located at the top of the window starting from the visible part).

Debug Assertion failed in dialog box,Visual c++

I am trying to add a bitmap image(.bmp) to background of a main Dialog in visual studio c++. I created a close button which normally works well but after putting background image and when I press close button I get this error:
Debug assertion failed.
File:c:\program files(x86)\microsoft visual
studio12.0\vc\atlmfc\include\atlwin.h
Line:3604 Expression:m_hWnd==0
For information on how your program can cause an assertion failure,
see the Visual C++ documantation an asserts.
Abort Retry Ignore
For loading bitmap image a class defined.
Header:
#if !defined(AFX_PICTUREWINDOW_H__44323373_9E89_11D3_A393_00C0DFC59237__INCLUDED_)
#define AFX_PICTUREWINDOW_H__44323373_9E89_11D3_A393_00C0DFC59237__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <atlbase.h>
#include <atlwin.h>
class CPictureWindow : public CWindowImpl<CPictureWindow>
{
public:
typedef enum HandlerTypeEnum
{
ClientPaint = WM_PAINT,
BackGroundPaint = WM_ERASEBKGND
} HandlerTypeEnum;
CPictureWindow()
{
m_nMessageHandler = ClientPaint;
};
virtual ~CPictureWindow()
{
};
BEGIN_MSG_MAP(CPictureWindow)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkGnd)
END_MSG_MAP()
virtual BOOL Load(LPCTSTR szFileName)
{
BOOL bResult = FALSE;
Close();
if (szFileName)
{
OFSTRUCT of;
HANDLE hFile = NULL;;
if ((hFile = (HANDLE)OpenFile((LPCSTR)szFileName, &of, OF_READ | OF_SHARE_COMPAT)) != (HANDLE)HFILE_ERROR)
{
DWORD dwHighWord = NULL, dwSizeLow = GetFileSize(hFile, &dwHighWord);
DWORD dwFileSize = dwSizeLow;
HRESULT hResult = NULL;
if (HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, dwFileSize))
if (void* pvData = GlobalLock(hGlobal))
{
DWORD dwReadBytes = NULL;
BOOL bRead = ReadFile(hFile, pvData, dwFileSize, &dwReadBytes, NULL);
GlobalUnlock(hGlobal);
if (bRead)
{
CComPtr<IStream> spStream;
_ASSERTE(dwFileSize == dwReadBytes);
if (SUCCEEDED(CreateStreamOnHGlobal(hGlobal, TRUE, &spStream)))
if (SUCCEEDED(hResult = OleLoadPicture(spStream, 0, FALSE, IID_IPicture, (void**)&m_spPicture)))
bResult = TRUE;
}
}
CloseHandle(hFile);
}
}
Invalidate();
return bResult;
}
HandlerTypeEnum m_nMessageHandler;
protected:
inline virtual BOOL IsHandlerMessage(UINT uMsg)
{
return m_nMessageHandler == (HandlerTypeEnum)uMsg;
}
void PutPicture(IPicture* pPicture, HDC hDC, RECT rPicture)
{
OLE_XSIZE_HIMETRIC nWidth = NULL; OLE_YSIZE_HIMETRIC nHeight = NULL;
pPicture->get_Width(&nWidth); pPicture->get_Height(&nHeight);
pPicture->Render(hDC, rPicture.left, rPicture.top, rPicture.right - rPicture.left, rPicture.bottom - rPicture.top, 0, nHeight, nWidth, -nHeight, NULL);
};
LRESULT OnEraseBkGnd(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (IsHandlerMessage(uMsg))
{
if (m_spPicture)
{
BeginPaint(NULL);
RECT r; GetClientRect(&r);
HDC hDC = GetDC();
HWND hWndChild = GetWindow(GW_CHILD);
while (::IsWindow(hWndChild))
{
if (::IsWindowVisible(hWndChild))
{
RECT rChild; ::GetWindowRect(hWndChild, &rChild);
ScreenToClient(&rChild);
ExcludeClipRect(hDC, rChild.left, rChild.top, rChild.right, rChild.bottom);
}
hWndChild = ::GetWindow(hWndChild, GW_HWNDNEXT);
}
PutPicture(m_spPicture, hDC, r);
ReleaseDC(hDC);
EndPaint(NULL);
return TRUE;
}
}
bHandled = FALSE;
return FALSE;
};
LRESULT OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (IsHandlerMessage(uMsg))
{
if (m_spPicture)
{
BeginPaint(NULL);
RECT r; GetClientRect(&r);
HDC hDC = GetDC();
PutPicture(m_spPicture, hDC, r);
ReleaseDC(hDC);
EndPaint(NULL);
}
}
bHandled = FALSE;
return NULL;
};
void Close()
{
m_spPicture = NULL;
}
//Attributes
CComPtr<IPicture> m_spPicture;
};
#endif
and in DoDataExchange of .Cpp file:
objPictureWindow.SubclassWindow(m_hWnd);
objPictureWindow.m_nMessageHandler = CPictureWindow::BackGroundPaint;
objPictureWindow.Load((LPCTSTR)"D:\\bitmap2.bmp");
Size of this bitmap is about 2Mb. However I resized it to 500Kb but again I had the same error after pressing the close button to close this dialog.
By following this error compiler shows this line to me:
template <class TBase, class TWinTraits>
BOOL CWindowImplBaseT< TBase, TWinTraits >::SubclassWindow(_In_ HWND hWnd)
{
ATLASSUME(m_hWnd == NULL);
ATLASSERT(::IsWindow(hWnd));

How to check if an other program is running in fullscreen mode, eg. a media player

How can I check if an other app is running in full screen mode & topmost in c++ MFC?
I just want to disable all of my auto dialogs (warnings) if media player or other players are running. (Like silent/gamer mode in Avast.)
How could I do that?
Thank you.
using a combination of EnumWindows, GetWindowInfo and GetWindowRect does the trick.
bool IsTopMost( HWND hwnd )
{
WINDOWINFO info;
GetWindowInfo( hwnd, &info );
return ( info.dwExStyle & WS_EX_TOPMOST ) ? true : false;
}
bool IsFullScreenSize( HWND hwnd, const int cx, const int cy )
{
RECT r;
::GetWindowRect( hwnd, &r );
return r.right - r.left == cx && r.bottom - r.top == cy;
}
bool IsFullscreenAndMaximized( HWND hwnd )
{
if( IsTopMost( hwnd ) )
{
const int cx = GetSystemMetrics( SM_CXSCREEN );
const int cy = GetSystemMetrics( SM_CYSCREEN );
if( IsFullScreenSize( hwnd, cx, cy ) )
return true;
}
return false;
}
BOOL CALLBACK CheckMaximized( HWND hwnd, LPARAM lParam )
{
if( IsFullscreenAndMaximized( hwnd ) )
{
* (bool*) lParam = true;
return FALSE; //there can be only one so quit here
}
return TRUE;
}
bool bThereIsAFullscreenWin = false;
EnumWindows( (WNDENUMPROC) CheckMaximized, (LPARAM) &bThereIsAFullscreenWin );
edit2: updated with tested code, which works fine here for MediaPlayer on Windows 7. I tried with GetForeGroundWindow instead of the EnumWindows, but then the IsFullScreenSize() check only works depending on which area of media player the mouse is in exactly.
Note that the problem with multimonitor setups mentioned in the comment below is still here.
in my oppinion a very little improvement
bool AreSameRECT (RECT& lhs, RECT& rhs){
return (lhs.bottom == rhs.bottom && lhs.left == lhs.left && lhs.right == rhs.right && lhs.top == rhs.top) ? true : false;
}
bool IsFullscreenAndMaximized(HWND hWnd)
{
RECT screen_bounds;
GetWindowRect(GetDesktopWindow(), &screen_bounds);
RECT app_bounds;
GetWindowRect(hWnd, &app_bounds);
if(hWnd != GetDesktopWindow() && hWnd != GetShellWindow()) {
return AreSameRECT(app_bounds, screen_bounds);
}
return false;
}
And thanks to priviose answer
BOOL CALLBACK CheckFullScreenMode ( HWND hwnd, LPARAM lParam )
{
if( IsFullscreenAndMaximized(GetForegroundWindow()) )
{
* (bool*) lParam = true;
std::cout << "true";
return FALSE;
}
return TRUE;
}
int main() {
bool bThereIsAFullscreenWin = false;
EnumWindows( (WNDENUMPROC) CheckFullScreenMode, (LPARAM) &bThereIsAFullscreenWin );
}