1. 程式人生 > >新字型的永久註冊

新字型的永久註冊

CString GetCurrentModuleDir()
{
	TCHAR szPath[MAX_PATH + 1] = { 0 };
	if (0 == ::GetModuleFileName((HMODULE)&__ImageBase, szPath, MAX_PATH))
		return L"";

	::PathRemoveFileSpec(szPath);

	CString strDir = szPath;
	return strDir;
}

void PathAddBackslashEx(CString& strPath)
{
	CString strTemp;
	strTemp = strPath.Right(1);

	if (strTemp != _T("\\") && strTemp != _T("/"))
		strPath.Append(_T("\\"));
}

void RegisterPermanentFonts(const CString& strFontName, const CString& strFontFileName)
{
	//獲取字型檔案路徑,假定字型檔案放在exe的同級目錄
	CString strExistingFilePath = GetCurrentModuleDir() + strFontFileName;
	if (FALSE == ::PathFileExists(strExistingFilePath))
		return;

	WCHAR szFontDir[MAX_PATH] = { 0 };
	SHGetFolderPath(NULL, CSIDL_FONTS, NULL, 0, szFontDir);
	CString strFontDir = szFontDir;
	PathAddBackslashEx(strFontDir);
	CString strNewFilePath = strFontDir + strFontFileName;

	//1. 拷貝字型檔案
	::CopyFile(strExistingFilePath, strNewFilePath, FALSE);

	//臨時加入生效
	AddFontResource(strFontFileName);

	//永久使用註冊
	CRegKey reg;
	LONG lRet=0;
	lRet = reg.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"), KEY_READ | KEY_WRITE);
	if (lRet == ERROR_SUCCESS)
	{
		CString strFullFontName = strFontName;
		strFullFontName += _T(" (TrueType)");
		reg.SetStringValue(strFontName, strFontFileName);
	}
	reg.Close();

	//發廣播通知,超時退出
	::SendMessageTimeout(HWND_BROADCAST, WM_FONTCHANGE, 0, 0, SMTO_ABORTIFHUNG | SMTO_BLOCK, 5000, NULL);
}

int _tmain(int argc, _TCHAR* argv[])
{
	RegisterPermanentFonts(L"XXXXXXX", L"XXXXXXX.ttf");
	return 0;
}