⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 formatbar.shtml

📁 mfc资源大全包含MFC编程各个方面的源码
💻 SHTML
📖 第 1 页 / 共 2 页
字号:
<HTML>
<HEAD>
   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
   <META NAME="Author" CONTENT="Zafir Anjum">
   <TITLE>Rich Edit Control - Providing a Format toolbar</TITLE>
</HEAD>
<body background="../fancyhome/back.gif" bgcolor="#FFFFFF" link="#B50029" vlink="#8E2323" alink="#FF0000" bgproperties="fixed">
<table WIDTH="100%">
<tr WIDTH="100%">
<td align=center><!--#exec cgi="/cgi/ads.cgi"--><td>
</tr>
</table>


<CENTER>
<H3>
<FONT COLOR="#AOAO99">Providing a Format toolbar</FONT></H3></CENTER>

<HR>

A rich edit control without UI to change the character and paragraph formatting is not really very useful as a rich text editor. In this section we will develop code for a Format toolbar that can be used with a CRichEditView derivative. There is no hard link between the toolbar itself and the CRichEditView, so we can even use this toolbar with a sub-class of CRichEditCtrl. The only extra work would be to make sure that some of the notifications sent by the toolbar gets forwarded to the control.

<P>There is a huge scope for improvement in the code given here, but intergrating this in your application should be fairly easy. When you feel that you need more functionality out of the Format toolbar, take a look at the WordPad sample that comes with your Visual C++ CD. This sample is the actual source code for the WordPad applet that ships with Windows. Be warned though, it takes a little time to understand the code. 

<H4>Step 1: Create a toolbar control resource</H4>
The first thing we need to do is create a toolbar control resource. Actually you can create a toolbar from a bitmap but it is lot easier to work with a toolbar control. The resource editor has quite a good support for it.

<P>This is what the toolbar control looks like in the resource editor. Give the toolbar control resource the ID - IDR_FORMATBAR. Actually choose any name but you should be willing to replace all occurance of IDR_FORMATBAR in the code below with the new ID.


<P>The first two buttons are place holders for the Font Name combobox and the Font Size combobox. The other buttons are pretty obvious. Once we have the images, we should go ahead and set the properties. Besides specifying an ID for each button, we should also provide the prompt string. The prompt string is used for the help text that appears in the status bar and the tooltip text.



<P>The 'Toolbar Button Properties' dialog is shown above for the Font Name button. The table below lists suggested IDs and prompt strings - in the same sequence they appear in the toolbar.

<p>
<TABLE BORDER=1 WIDTH="100%" >
<TR><TD WIDTH="30%" BGCOLOR="#A0A0A0">ID</A></TD><TD WIDTH="70%" BGCOLOR="#A0A0A0">Prompt</TD></TR>
<TR><TD>IDC_FONTNAME</A></TD><TD>Changes the font of the selection\nFont</TD></TR>
<TR><TD>IDC_FONTSIZE</A></TD><TD>Changes the font size of the selection\nFont Size</TD></TR>
<TR><TD>ID_CHAR_BOLD</A></TD><TD>Makes the selection bold (toggle)\nBold</TD></TR>
<TR><TD>ID_CHAR_ITALIC</A></TD><TD>Makes the selection italics (toggle)\nItalic</TD></TR>
<TR><TD>ID_CHAR_UNDERLINE</A></TD><TD>Formats the selection with a continuous underline (toggle)\nUnderline</TD></TR>
<TR><TD>ID_CHAR_COLOR</A></TD><TD>Formats the selection with a color\nColor</TD></TR>
<TR><TD>ID_PARA_LEFT</A></TD><TD>Left-justifies paragraphs\nLeft Justify</TD></TR>
<TR><TD>ID_PARA_CENTER</A></TD><TD>Center-justifies paragraphs\nCenter Justify</TD></TR>
<TR><TD>ID_PARA_RIGHT</A></TD><TD>Right-justifies paragraph\nRight Justify</TD></TR>
<TR><TD>ID_INSERT_BULLET</A></TD><TD>Inserts a bullet on this line\nBullet</TD></TR>
</TABLE>


<H4>Step 2: Create a CFormatBar class</H4>
I used the Class Wizard to create this class. The class wizard did not have the option of specifying the CToolBar class as the base class, so I chose the CToolBarCtrl class as the base class and then in the source files, changed it to CToolBar. The advantage of using a CToolBar is that it is already hooked into the Doc-View architecture of MFC. This helps in updating the toolbar and the status bar.

<P>The code for the CFormatBar class header file is given below. You will notice that besides declaring the CFormatBar class, it also declares CHARNMHDR struct. This is used to send custom notification messages whenever the font name or the font size changes. The FN_SETFORMAT and FN_GETFORMAT defines are the custom notification message values. 

<P>The CFormatBar constructor takes a default value which is set to IDR_FORMATBAR. This is useful only if you already have a resource with the ID IDR_FORMATBAR that you are using for some other purpose.

<PRE><TT><FONT COLOR="#990000">#if !defined(AFX_FORMATBAR_H__76705223_1E1F_11D1_830C_5CB0BB000000__INCLUDED_)
#define AFX_FORMATBAR_H__76705223_1E1F_11D1_830C_5CB0BB000000__INCLUDED_

#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// FormatBar.h : header file
//



/////////////////////////////////////////////////////////////////////////////
// CFormatBar window

struct CHARNMHDR : public NMHDR
{
	CHARFORMAT cf;
	CHARNMHDR() {cf.cbSize = sizeof(CHARFORMAT);}
};

// Define format notifications constant
#define FN_SETFORMAT	0x1000
#define FN_GETFORMAT	0x1001


class CFormatBar : public CToolBar
{
// Construction
public:
	enum { IDD = IDR_FORMATBAR };
	CFormatBar(UINT nID = IDD );

// Attributes
public:

// Operations
public:

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CFormatBar)
	public:
	virtual BOOL PreTranslateMessage(MSG* pMsg);
	//}}AFX_VIRTUAL

// Implementation
public:
	virtual ~CFormatBar();

protected:
	void FillFontName( CDC *pDC );
	virtual void OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler);


protected:
	CComboBox	m_cmbFontName;
	CComboBox	m_cmbFontSize;

	// Generated message map functions
protected:
	afx_msg void OnSelectFontName();
	afx_msg void OnSelectFontSize();

	//{{AFX_MSG(CFormatBar)
	afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
	//}}AFX_MSG

	DECLARE_MESSAGE_MAP()

private:
	UINT nToolbarID;
	static int CALLBACK EnumFontFamProc(ENUMLOGFONT *lpelf, 
					NEWTEXTMETRIC *lpntm,
					int nFontType,
					LPARAM lParam);

};

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_FORMATBAR_H__76705223_1E1F_11D1_830C_5CB0BB000000__INCLUDED_)
</FONT></TT></PRE>


<P>The code in the implementation file for CFormatBar now follows.

<PRE><TT><FONT COLOR="#990000">/////////////////////////////////////////////////////////////////////////////
// FormatBar.cpp : implementation file
//

#include "stdafx.h"
#include "RichEdit.h"
#include "FormatBar.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CFormatBar

// Declare const array of font sizes
const static int nFontSizes[] = 
	{8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72};


CFormatBar::CFormatBar(UINT nID )
{
	nToolbarID = nID;
}

CFormatBar::~CFormatBar()
{
}


BEGIN_MESSAGE_MAP(CFormatBar, CToolBar)
	//{{AFX_MSG_MAP(CFormatBar)
	ON_WM_CREATE()
	//}}AFX_MSG_MAP
	ON_CBN_SELENDOK(IDC_FONTNAME, OnSelectFontName)
	ON_CBN_SELENDOK(IDC_FONTSIZE, OnSelectFontSize)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFormatBar message handlers

int CFormatBar::OnCreate(LPCREATESTRUCT lpCreateStruct) 
{
	if (CToolBar::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	// Load the toolbar
	if( !LoadToolBar( nToolbarID ) )
		return -1;


	// Get the average char width
	CClientDC dc(this);

	// Determine the size required by the font comboboxes
	// We will use the DEFAULT_GUI_FONT
	HGDIOBJ hFont = GetStockObject( DEFAULT_GUI_FONT );
	CFont font;
	font.Attach( hFont );
	dc.SelectObject( font );

	TEXTMETRIC tm;
	dc.GetTextMetrics( &tm );
	int cxChar = tm.tmAveCharWidth;
	int cyChar = tm.tmHeight + tm.tmExternalLeading;


	// Create the Font Name combo
	CRect rect; 
	GetItemRect( CommandToIndex(IDC_FONTNAME), &rect );
	rect.right = rect.left + (LF_FACESIZE+4)*cxChar;
	rect.bottom = rect.top + 16*cyChar;

	SetButtonInfo( CommandToIndex(IDC_FONTNAME), IDC_FONTNAME, 
				TBBS_SEPARATOR, rect.Width() );

	UINT nCreateStyle = WS_TABSTOP|WS_VISIBLE|WS_VSCROLL;
	if (!m_cmbFontName.Create(nCreateStyle|CBS_DROPDOWNLIST|CBS_SORT, 
		rect, this, IDC_FONTNAME))
	{
		TRACE0("Failed to create Font Name combo-box\n");
		return -1;
	}


	// Create Font Size combo
	GetItemRect( CommandToIndex(IDC_FONTSIZE), &rect );
	rect.right = rect.left + 10*cxChar;
	rect.bottom = rect.top + 16*cyChar;

	SetButtonInfo( CommandToIndex(IDC_FONTSIZE), IDC_FONTSIZE, 
				TBBS_SEPARATOR, rect.Width() );

	if (!m_cmbFontSize.Create(nCreateStyle|CBS_DROPDOWN|WS_HSCROLL, 
		rect, this, IDC_FONTSIZE))
	{
		TRACE0("Failed to create Font Size combo-box\n");
		return -1;
	}
	m_cmbFontSize.LimitText(4);


	// Set the font for the combo boxes to DEFAULT_GUI_FONT
	m_cmbFontName.SetFont(&font);
	m_cmbFontSize.SetFont(&font);

	// Fill the Font names in the Font Name combo
	::EnumFontFamilies( dc.m_hDC, NULL, (FONTENUMPROC)EnumFontFamProc, 
				(LPARAM) this );

	// Fill the Font Size combo
	CString sSize;
	int nSizeCount = sizeof(nFontSizes) / sizeof(nFontSizes[0]);
	for( int i=0; i < nSizeCount; i++ )
	{
		sSize.Format("%d", nFontSizes[i] );
		m_cmbFontSize.AddString( sSize );
	}

	return 0;
}

int CALLBACK CFormatBar::EnumFontFamProc(ENUMLOGFONT *lpelf, NEWTEXTMETRIC *lpntm,
					int nFontType, LPARAM lParam)
{
	CFormatBar* pWnd = (CFormatBar*)lParam;

	// Add the font name to the combo
	pWnd->m_cmbFontName.AddString(lpelf->elfLogFont.lfFaceName);

	return 1;		// 1 to continue enumeration
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -