【发布时间】:2023-04-02 14:34:01
【问题描述】:
我最近一直在学习 Win32 API 使用 this 教程。我一直在尝试创建一个窗口,该窗口基于它使用 Direct2D 显示一个圆圈。但是,程序不断抛出异常:
Exception thrown: read access violation.
**this** was nullptr.
VS 2019 然后打开 d2d1.h 到这个部分:
CreateHwndRenderTarget(
CONST D2D1_RENDER_TARGET_PROPERTIES &renderTargetProperties,
CONST D2D1_HWND_RENDER_TARGET_PROPERTIES &hwndRenderTargetProperties,
_COM_Outptr_ ID2D1HwndRenderTarget **hwndRenderTarget
)
{
return CreateHwndRenderTarget(&renderTargetProperties, &hwndRenderTargetProperties, hwndRenderTarget);
}
这是导致此问题的代码部分:
HRESULT CreateGraphicsResources(HWND hWnd) {
HRESULT hr = S_OK;
if (pRenderTarget == NULL) {
RECT rc;
GetClientRect(hWnd, &rc);
D2D1_SIZE_U size = D2D1::SizeU(rc.right, rc.bottom);
hr = pFactory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(hWnd, size),
&pRenderTarget);
if (SUCCEEDED(hr)) {
const D2D1_COLOR_F color = D2D1::ColorF(1.0f, 1.0f, 0);
hr = pRenderTarget->CreateSolidColorBrush(color, &pBrush);
if (SUCCEEDED(hr))
{
CalculateLayout();
}
}
}
return hr;
}
这是我调用函数的地方:
case WM_PAINT:
{
HRESULT hr = CreateGraphicsResources(hWnd);
if (SUCCEEDED(hr))
{
PAINTSTRUCT ps;
BeginPaint(hWnd, &ps);
pRenderTarget->BeginDraw();
pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::SkyBlue));
pRenderTarget->FillEllipse(ellipse, pBrush);
hr = pRenderTarget->EndDraw();
if (FAILED(hr) || hr == D2DERR_RECREATE_TARGET)
{
DiscardGraphicsResources();
}
EndPaint(hWnd, &ps);
}
}
那么,这个异常是什么意思,是什么导致它被抛出? 另外,我该如何解决? 谢谢您的帮助。 完整文件可在here 获得。
【问题讨论】:
-
我们不需要完整的代码。显示的代码是不够的。请提供minimal reproducible example。
-
嗯,它说。 “这个”是空指针。 “this”表示您调用该函数的对象。所以在
pFactory->CreateHwndRenderTarget(...)中是pFactory。那么为什么 pFactory 为空呢?
标签: c++ windows winapi direct2d