关于 locksource 后修改返回值报错的问题

之前有段代码,vs2010 运行正常,vs2019 运行之后程序异常。异常代码如下:

    DLGTEMPLATEEX* pTemplate;
	HINSTANCE hInst = ::AfxFindResourceHandle(MAKEINTRESOURCE(m_nEntityResID), RT_DIALOG);

	if (hInst == NULL)
	{ 
		TRACE("Cound not find resource in resource chain");
		ASSERT(FALSE);
		return;
	}

	HRSRC hRsrc = ::FindResource(hInst, MAKEINTRESOURCE(m_nEntityResID), RT_DIALOG);
	ASSERT(hRsrc != NULL);

	HGLOBAL hTemplate = ::LoadResource(hInst, hRsrc);
	ASSERT(hTemplate != NULL);

	pTemplate = (DLGTEMPLATEEX*)::LockResource(hTemplate);

	// Save original style
	DWORD dwSaveStyle = pTemplate->style;
	DWORD dwSaveExStyle = pTemplate->exStyle;

	// Modify styles
	pTemplate->style = (pTemplate->style & ~(WS_POPUP | WS_CAPTION | WS_THICKFRAME| DS_MODALFRAME)) | DS_CONTROL | WS_CHILD | WS_VISIBLE;
	pTemplate->exStyle = pTemplate->exStyle | WS_EX_CONTROLPARENT;

	// Create it!!!
	m_pContainerDialog->CreateIndirect(pTemplate, this);

	// Restore original style
	pTemplate->style = dwSaveStyle;
	pTemplate->exStyle = dwSaveExStyle;

	// Get caption from template
	SetWindowText((wchar_t*)((BYTE*)pTemplate + sizeof(DLGTEMPLATEEX) + 4));		// 4 bytes reserved for menu and wndclass

	::UnlockResource(hTemplate);
	::FreeResource(hTemplate);

异常位置为 ModifySytles 的位置。

异常原因:

LockResource 获取得到的资源对象为只读,不能对其修改。如果想使用该资源,需要将资源对象拷贝一份然后就行修改使用。

修改后代码如下:


	DLGTEMPLATEEX* pTemplate;
	HINSTANCE hInst = ::AfxFindResourceHandle(MAKEINTRESOURCE(m_nEntityResID), RT_DIALOG);

	if (hInst == NULL)
	{ 
		TRACE("Cound not find resource in resource chain");
		ASSERT(FALSE);
		return;
	}

	HRSRC hRsrc = ::FindResource(hInst, MAKEINTRESOURCE(m_nEntityResID), RT_DIALOG);
	ASSERT(hRsrc != NULL);

	HGLOBAL hTemplate = ::LoadResource(hInst, hRsrc);
	ASSERT(hTemplate != NULL);

	pTemplate = (DLGTEMPLATEEX*)::LockResource(hTemplate);

	// Save original style
	const DWORD dwSaveStyle = pTemplate->style;
	const DWORD dwSaveExStyle = pTemplate->exStyle;

	DWORD dwSize = SizeofResource(hInst, hRsrc);
	DLGTEMPLATEEX* pTempTemplate = (DLGTEMPLATEEX*)malloc(dwSize);
	if (pTempTemplate != nullptr)
	{
		memcpy(pTempTemplate, pTemplate, dwSize);

		// Modify styles
		pTempTemplate->style = (pTemplate->style & ~(WS_POPUP | WS_CAPTION | WS_THICKFRAME | DS_MODALFRAME)) | DS_CONTROL | WS_CHILD | WS_VISIBLE;
		pTempTemplate->exStyle = pTemplate->exStyle | WS_EX_CONTROLPARENT;

		// Create it!!!
		m_pContainerDialog->CreateIndirect(pTempTemplate, this);

		// Restore original style
		pTempTemplate->style = dwSaveStyle;
		pTempTemplate->exStyle = dwSaveExStyle;

		// Get caption from template
		SetWindowText((wchar_t*)((BYTE*)pTempTemplate + sizeof(DLGTEMPLATEEX) + 4));		// 4 bytes reserved for menu and wndclass
		free(pTempTemplate);

 

你可能感兴趣的:(vc,界面开发,windows)