Exercise COMMON family (reposted) in VC

zhaozj2021-02-16  66

Chapter 6 Exercises CToolbar

6.1 Main functions of tool strip control

The so-called toolbar is a set of command buttons with bitmap and separators, and the bitmap button portion can be a down button, check the box button, a wireless button, and the like. The tool bar object class is derived from the main window frame CFRAMEWND or CMDIFrameWnd, and its class control ctoolbar :: getToolbarctrl is a member function in the MFC class library, allowing the general control and additional functionality provided in the class library, CToolbar class control member Control provides all the features of Windows General Control, however, after the reference is obtained by calling the GetToolbarCtrl member function, the toolbar can make the tool strip more feature.

The creation of the toolbar has four steps: first to establish toolbar resources; then establish a toolbar object structure; secondly build toolbar objects and bind by calling the establishment function; finally call LoadToolbar to transfer tool strip resources.

In addition, it can also be established by the method of directly load the bit map, the steps are as follows: first establish a toolbar object; then establish a toolbar and bind object by calling the establishment function; secondly tune the bitmap containing the button; finally uses the setButtons function settings The style of the button is connected to the bitmap.

Where all the button bitmaps are stored in a bitmap file, the button bitmap is the same, the default is 16-point width, 15 points high, the bitmap must be stored from left to right. The setting button function has a pointer and an index value to a set of control identifier IDs, used to determine the location of each button, if there is a separator ID_seParetor, then the image does not exist the index value. Under normal circumstances, the buttons in the toolbar are arranged in a single row from left to right, and the sorting rules can be changed via the setButtonInfo function. The final buttons in the toolbar are the same, all of which are 24 x 22 pixels, each button is only an image. The button in the toolbar is default the push button, and the check box button can be implemented by setting the TBBS_CHECKBOX style, and the wireless button can be implemented by calling the SetRadio member function.

6.2 Toolbar Controlled Object Structure

6.2.1 Object Structure of Toolbars

6.2.1.1 Establishment of tool bars

CToolbar & Toolbar build tool bar object structure

CREATE Create tool bar objects and bind

Tools Ctelet CToolbar :: Create The call format is as follows:

BOOL CREATE (CWND * PParentWnd, DWORD DWSTYLE = WS_CHILD | WS_VISIBLE | CBRS_TOP,

UINT NID = AFX_IDW_TOOLBAR);

The parameter pParentWnd is used to determine the pointer to the tool strip-parent window; the parameter dWStyle is used to determine the style of the toolbar, and the value is as follows; the parameter NID is used to determine the identifier of the tool strip window.

CBRS_TOP represents the top of the toolbar on the frame window

CBRS_BOTTOM represents the bottom of the toolbar on the frame window

CBRS_NOALIGN means that the toolbar changes in the parent window and does not respond

CBRS_ToolTIPS indicates that the toolbar has a dynamic prompt function.

CBRS_SIZE_DYNAMIC indicates that the toolbar is static and cannot be changed.

CBRS_SIZE_FIXED indicates that the toolbar is dynamic to change

CBRS_FLOATING means the toolbar is floating

CBRS_FLYBY indicates information on the button on the toolbar on the status bar.

CBRS_HIDE_INPLACE indicates toolbar hide

In addition to the above functions, the size of the setting buttons and bitmaps, setting the height of the toolbar, Tool Source LOADTOOLBAR, Tutore Toolbar Buttap LoadBitmap, Set Toolbar Buttap SetBitmap, Set Toolbar The mode of control functions such as the style of the median button and the index value setButtons. 6.2.1.2 Class Attributes of Tools

The properties of the toolbar control class include obtaining the identifier ID object button index CommandToIndex, obtain the index corresponding to the command identifier ID or separator GetItemID, get the rectangular area GetItemRect corresponding to the index, get the button style getButtonStyle, set the button style setButtonStyle, get button ID ID - Style - Image Number GetButtonInfo, Set Button Id Identity - Style - Image Number SetButtonInfo, get button prompt text getButtonTontext, set button Tips text setButtonText and acquisition toolbar directly access control GetToolbarCtrl et al.

6.2.2 Toolbar Control Object Structure

6.2.2.1 Establishment method of tool strip control

CToolBarctrl & Toolbarctrl Establishing Toolbar Control Object Structure

CREATE Establish toolbar control objects and bound

The call format for the toolbar control class ctoolbarctrl :: CREATE is as follows:

Bool Create (DWORD DWSTYLE, CONST RECT & RECT, CWND * PPARENTWND, UINT NID);

The parameter DWStyle is used to determine the style of the toolbar control, and there must be a WS_CHILD style; the parameter RECT is used to determine the size and position of the toolbar control; the parameter pParentWnd is used to determine the parent window pointer controlled by the toolbar, cannot be null; parameter NID To determine the identifier of the toolbar control.

You can use WS_CHILD, WS_VISIBLE and WS_DISABLED to set the style of the toolbar window, but must be reasonably set up as follows:

CCS_ADJUSTABLE allows the user to handle the toolbar window size, if there is a toolbar window, you must handle the correspondence

CCS_BOTTOM makes control at the bottom of the parent window customer area and is equally wide to the window.

CCS_NODIVIDER prohibits highlight strips for 2 pixels on top of the control

CCS_NOHILITE prohibits highlights of 1 pixels in the top of the control

CCS_NOMOVEY automatically aligns control change the size and movement, and vertically aligned must handle WM_SIZE messages.

If the CCS_NORSIZE style is valid, the style is invalid

CCS_noparentAlign prohibition control is automatically moved to the top or bottom of the parent window, if CCS_TOP or CCS_BOTTOM style

Valid, the height adjustment is default and the width can change

CCS_NORSIZE uses the default width and height value when setting new size or invalid values, and uses the creation value

CCS_TOP causes control to automatically stop at top of the parent window customer area and the same width as the parent window.

Finally, you must also use the following style to control the toolbar.

TBStyle_ToolTIPS enables toolbars to establish and manage dynamic prompt control

TBStyle_wrapable enables the toolbar control button to have multi-line arrangements

6.2.2.2 Data Structure in Toolbar Control

The most commonly used data structure in the toolbar control is TBButton, and the specific structure is as follows:

Typedef struct _tbbutton {

INT ibitmap; // Based on 0 bit map index value

INT IDCOMMAND; / / button Press the command value sent when

Byte fsState; // button status

Byte fsStyle; // button style

DWORD DWDATA; // Application defined data

INT istring; // Based on 0 button label string index value} tbutton;

Where the value of the button state fsstate is as follows:

TBSTATE_CHECKED indicates that the button has a TBStyle_Checked style and pressed

TBSTATE_ENABLED indicates that the button allows you to accept the input, otherwise it will be grayed without accepting any input.

TBSTATE_HIDEN indicates that the button is not visible and does not accept any input

TBSTATE_INDETERMINATE indicates that the button is grayish

TBSTATE_PRESSED indicates that the button is pressed.

The TBSTATE_WRAP indicates that the button has a wrap character, and the button must have a TBSTATE_ENABLED state.

Button Style Style can be a combination of the following values:

TBStyle_Button represents the establishment of a standard push button

TBStyle_Check Represents the establishment check status button

TBStyle_CheckGroup represents the establishment check button group

TBStyle_Group Represents to establish a status button group

TBStyle_sep Represents a button separator

6.2.2.3 Tool strip control class properties

The tool bar control class property inevitably contact judgment button enables the status isbuttonNabled, the determination button Check the status isbuttonChecked, the determination button Press the status isbuttonpressed, the determination button hides whether the ISButtonHidden, the determination button Goomery isbuttonIndeeeterminate, set the button status setstate, get button status GetState, getting button information getButton, getting button total number getButtonCount, getting button rectangular region GetItemRect, setting button structure size SetButtonStructSize, setting button size SetButtonSize, setting button bitmap size SetBitmapSize, getting button display control GetToolTips, the Setup button presentation control SetToolTips like.

6.2.2.4 Toolbar Control Class Operation Method

The toolbar control class includes enabling the button EnableButton, check the button CheckButton, Press the button PressButton, hide the button Hidebutton, the gray button Indeterminate, add button addbuttons, insert button INSERTBUTTON, the delete button deletebutton, acquire the index corresponding to the control ID CommandToIndex, Recovery Tools Status RESTORESTATE, Save Toolboot Status SaveState and Removing Tools Size AutoSize, etc.

6.3 Application Skills for Toolbar Control

It can be said that the toolbar and the above common control are an indispensable functional element in the application, and its advantages and disadvantages will directly affect the basic functions and operational characteristics of the program. So here will set up the tool bar's use techniques in terms of the establishment of the toolbar, state preservation and recovery, planar characteristics, stop position, sorting method, message mapping, status update, control usage, and attribute control.

6.3.1 Establishing Tips for Tools

6.3.1.1 Establishment method of common tools

If the application has a toolbar when it is created, you can meet the requirements of simple increases, modifications, and delete, such as button icons in the toolbar. If you do not establish or want to add other tools, you should follow the steps.

First open the established single document-based framework engineering file ctool and select "Insert-> Resource-> Toolbar" option, insert the toolbar resources and set the resource identifier; then edit the button icon in the toolbar and the corresponding button ID. Value, and use the class wizard classwizard to add two processing functions for the button message; add and modify the dynamic prompts of the toolbar icon in the resource file; Open Mainfrm.h Contains files after "CToolbar M_WndmainToolbar" increase "CToolbar" M_WndtestToolbar ", etc., to create an increased toolbar object; set the member variables required for the establishment function in Mainfrm.h, such as the color variable is m_bcolor, dynamic prompt function variables are m_btooltips, etc., pay attention to the parameters that the member variable name and it should be In order to use; finally in the oncreate () setup function in Mainfrm.cpp, add control code as follows: 1 The specific steps are as follows: 1 Add tool bar object control and member variables in mainfrm.h

#define Toolleft 18

Class CMAINFRAME: PUBLIC CFRAMEWND

... // Other code

PUBLIC:

BOOL M_BTOOLTIPS; / / Tools Tips

... // Other code

protected: // Toolbar Controls Member Variables

CSTATUSBAR M_WNDSTATUSBAR;

File: // Status of the framework

CTestToolBar M_WndmainToolbar; // Framework Toolbar

Ctesttoolbar M_WndtestToolbar; // New Toolbar

Ctesttoolbar M_WnddockToolbar; // Floating Toolbar

Ctesttoolbar M_WnddockNextBar; // Floating Toolbar

... // Other code

}

The control class of the toolbar in the frame program should normal CToolbar, which can be the derived class CTestToolbar designed (for the new tool strip control class name after the ability to expand plane characteristics), and depending on the actual needs. With the CDIALOGBAR class and the CStylebar class, you can also establish a toolbar of the extended type. For details, please control the application skills in the Back toolbar, but must be in the header of the file.

Contains the following command:

#ifndef __afxext_h__

#include // Access CToolbar and CSTATUSBAR directly

#ENDIF

2 Perfect window establishment functions in mainfrm.cpp

INT CMAINFRAME :: OnCreate (lpcreatestruct lpcreatestruct)

{If (cframewnd :: oncreate (lpcreatestructure) == -1)

Return -1;

WindowPlacement WP; // Save the main window and toolbar window position status

IF (READWINDOWPLACEMENT (& WP)) // Read position status information

SetwindowPlacement;

File: // Set location status information

m_btooltips = (AFXGetApp () -> getprofileint (// read prompt function

_T ("general"), _ t ("tooltips"), 1)! = 0);

File: // The default is 1

m_wndmaintoolbar.setState (Toolleft, True); // Setting the initial state

Enabledocking (CBRS_ALIGN_ANY); // Stop position, must be in advance

IF (! m_wndmaintoolbar.create (this, ws_child | ws_visible | cbrs_size_dynamic | cbrs_top | ((m_btooltips)?

(CBRS_ToolTIPS | CBRS_FLYBY): 0), IDR_MAINFRAME ||

! m_wndmaintoolbar.loadtoolbar (idR_maInframe))

{

File: // CBRS_SIZE_DYNAMIC is a lock position style

Trace0 ("Main Tools Mainframe Established Fail / N");

Return -1;} // Establish failure processing

... // Establish another toolbar code, basically the same

IF (! m_wndstatusbar.create (this) ||

M_WndStatusBar.setindicators (Indicators,

SIZEOF (INDICATORS) / SIZEOF (UINT))))

{

File: // Establish a status bar

Trace0 ("Failed to Create Status Bar / N);

Return -1;} // fail to create

m_wndmaintoolbar.SetWindowText (_t ("Main Toolbar")); // Setting Title

m_wndmaintoolbar.enabledocking (cbrs_align_any); // Stop location

File: //m_wndmaintoolbar.ModifyStyle (0, TBStyle_FLAT); // Plane Features

... // Set other toolbar position code, basically the same

DockControlbar (& M_WndmainToolbar,

AFX_IDW_DOCKBAR_TOP); // Lock position

DockControlbarleftof (& M_WndtestToolbar,

& m_wndmaintoolbar); / / Connection Toolbar

DockControlbar (& M_WndDockToolbar, AFX_IDW_DOCKBAR_RIGHT);

M_WnddockToolBar.SetColumns (AfxGetApp () -> getprofileint

_T ("General"), _ T ("Column"), 3)); // Restore column format, default is 3

DockControlbarleftof (& M_WnddockNextBar, & m_wnddocktoolbar);

M_WnddockNextBar.SetColumns (AFXGetApp () -> getprofileint

_T ("General"), _ T ("Column"), 3));

Loadbarstate (_T ("general")); // Restore the status and location

Return 0;

}

The above established process except for the toolbar establishment and resource call functions, the status saving and recovery functions of the window and toolbar, the registry parameter read function, the toolbar stop position function, the toolbar title modification function, toolbar connection function , The tool stroll format control function and tool strip style modification function, where the style setting in the toolbar establishment function is important. If the established toolbar needs to reset the multi-column sorting function, in addition to correctly set the toolbar stop position parameters In addition, it is necessary to set the CBRS_SIZE_FIXED style, that is, the program allows the program to change the size of the toolbar window. If the toolbar does not need to reorder, you must be set to the CBRS_SIZE_DYNAMIC style, otherwise the toolbar can not only reorder and correctly stop to the ideal location, and It is also not possible to properly save and restore the position and status of the tool bar, which should cause the programmer to attach great importance to it. The remainder is introduced.

6.3.1.2 Establishment of floating tools

If you want to create a floating toolbar, you must use the tool bar of the tool bar: CPOINT PT (GetSystemMeen) -100, GetSystemmetrics / 3);

FloatControlbar (& M_Wndpalettebar, Pt); // Floating Toolbar

6.3.1.3 Method for establishing multi-bit map tools

If the tool bar exists, such as monochrome and color, etc., the toolbar button must be present in the bitmap resource file instead of the toolbar resources, and the following:

IF (! m_wnddocktoolbar.create (this, ws_child | ws_visible |

CBRS_SIZE_FIXED | CBRS_TOP | CBRS_ToolTIPS, ID_PALETTEBAR) ||

! m_wnddocktoolbar.loadbitmap (idR_docktoolbar) ||

M_WnddockToolBar.SetButtons (Docktool,

SIZEOF (Docktool) / sizeof (uint)))))

Where DockTool is a button IDS data structure, its definition method is as follows:

Static uint based_code docktool [] =

{ID_SEPARATOR,

ID_Style_Left,

ID_Style_Centered,

ID_Style_Right,

ID_Style_Justified,

}

The enabledocking function in the above established process must be placed before all the toolbar established a function, otherwise it may have a hard discovery error, such as the initial position control of the special tool strip. All features of the toolbar are determined in the above setup function, so its establishment process is a key link to implement the ideal toolbar.

6.3.2 Tools Status Save and Recovery 6.3.3

Many applications have functions of saving and restoring applications and their tool bars. That is, after the next startup application enters the last run state, this feature is only necessary to perform an interface layout. It is convenient for users.

To properly save and restore the application interface status, you must save and recover all the application window and toolbar window, which requires the establishment of the application and the shutdown process. Specific steps are as follows:

(1) First Using the Class Wizard ClassWizard to add a window to the application to turn off the WM_CLOSE message processing function onclose ();

(2) Set a member variable for the application status in mainfrm.cpp

Static tchar based_code szsection [] = _ t ("settings");

Static tchar based_code szwindowpos [] = _ t ("WindowPOS");

Static tchar szformat [] = _ t ("% U,% U,% D,% D,% D,% D,% D,% D,% D,% D");

(3) Preparation window position status reading and writing functions

Static Bool Pascal Near ReadWindowPlacement (LPWindowPlacement PWP)

{

File: // Window position status Read function, from ini file

CString strbuffer = AFXGetApp () -> getProfileString (Szsection, SzWindowPos);

IF (strBuffer.isempty ()) Return False;

WindowPlacement WP; // Window location data structure

INT nread = _stscanf (strbuffer, szformat,

& wp.flags, & wp.showcmd, / / ​​Read numeric values ​​for data structures

& wp.PtMinPosition.x, & wp.ptmaxposition.x, & wp.ptmaxPosition.y,

& wp.rcnormalPosition.Left, & wp.rcnormalPosition.top,

& wp.rcnormalPosition.right, & wp.rcnormalposition.bottom

IF (NREAD! = 10) Return False;

wp.Length = SizeOf WP; // Structural size

* PWP = WP;

File: // Structural pointer

Return True;

}

Static void Pascal Near WriteWindowplacement

LPWindowPlacement PWP)

{

File: // Window position status write function, write to the INI file

TCHAR SZBUFFER [SIZEOF ("- 32767") * 8 SIZEOF ("65535") * 2];

WSPrintf (SZBuffer, SzFormat, // converts the parameter value to string

PWP-> Flags, PWP-> showcmd,

PWP-> PTMINPSITION.X, PWP-> PTMINPSITION.Y,

PWP-> ptmaxposition.x, pwp-> ptmaxposition.y,

PWP-> rcnormalposition.left, pwp-> rcnormalposition.top,

PWP-> rcnormalposition.right, pwp-> rcnormalposition.bottom;

AFXGetApp () -> WriteProfileString (SzseProfileString (Szsection, SzwindowPos, Szbuffer);

}

(4) Add status reading and setting functions in the application establishment function on -create ()

WindowPlacement WP; // Save the main window and toolbar window position status

IF (READWINDOWPLACEMENT (& WP)) // Read position status information

SetwindowPlacement;

File: // Set location status information

(5) Add Toolbar Status Recovery Function in Application Function OnCreate ()

M_WnddockToolBar.SetColumns (AfxGetApp () -> getprofileint

_T ("General"), _ T ("Column"), 3)); // Restore column format, default is 3

M_WnddockNextBar.SetColumns (AFXGetApp () -> getprofileint

_T ("General"), _ T ("Column"), 3));

Loadbarstate (_T ("general")); // Restore the status and location

(6) Perfect status save function in the application closing function onclose ()

Void cmainframe :: onClose ()

{

File: // Save the state of the toolbar, etc.

Savebarstate (_T ("general")); // Save tool strip status

AFXGetApp () -> WriteProfileint (_t ("general"), // Write column number

_T ("columns"), m_wnddocktoolbar.getColumns ());

AFXGetApp () -> WriteProfileint (_T ("general"),

_T ("Tooltips"), (m_btooltips! = 0)); // Write prompt function WindowPlacement WP;

WP.LENGTH = SIZEOF WP;

IF (GetWindowplacement (& WP)) {

WP.FLAGS = 0;

IF (iszoomed ()) wp.flags | = WPF_RESTORETOMAXIMIZED;

File: // If the window is enlarged, save to maximize the status.

WriteWindowPlacement (& WP);

}

CframeWnd :: onClose ();

}

Although the SaveBarstate () and loadbarstate () function saves and restores all the default location status of the toolbar, the actual functional parameter sections you implement cannot be saved, so the saving code of these parameters should be written separately, such as the arrangement of the toolbar Format column parameter, color status flag, and whether there is a dynamic prompt function flag, etc., you must pay attention when actually programmed.

6.3.4 Flat Characteristics of Toolbars

The flat feature of the toolbar gives a sense of refreshing, and the tools in many large applications use this feature and have achieved great success. Using the COMCTL32.DLL dynamic link library in VC 5, the main solution, which is the main solution includes: Since the MFC uses the style control bit to control the appearance of the toolbar, this cannot be set directly when establishing a toolbar. The style must be modified by the setflatlookStyle () function after the establishment; the toolbar control itself does not draw the separation line between the stages, and another task is to intercept the WM_PAINT message and increase the separation line at the corresponding location; Control does not draw the left handle (Gripper), the last task is to adjust the customer area and draw and draw the corresponding gripper.

Obviously, the above method supported by dynamic link library COMCTL32.DLL is inconvenient in actual work. Although the easiest way is to use the unusable toolbar style TBStyle_flat in VC 5, you can get the planar characteristics of the toolbar, just simply add one code "M_WndmaintoolBar.ModifyStyle (0, TBSTYLE_FLAT) after the toolbar is established, but The author found that this method has two serious errors: one is that the established flat tool strip is moving, it cannot automatically clear the button icon before the movement, so that the toolbar screen is messy; its second is the established plane toolbar When there is a floating property, the entire application window will automatically disappear as long as the mouse pointer moves to the floating tool bar. So the second method is not feasible. The best way to achieve a flat tool bar is to complete it in derived class. Although this process is more difficult to do, it is difficult for ordinary users, but if there is a perfect planar tool strip control class, add corresponding to the corresponding application The control class is a very easy thing. Below is the step of achieving perfect plane tools:

(1) First Using the Class Wizard ClassWizard to derive a new class CTestToolbar for the toolbar control class, and set the corresponding derived class implementation file name. Since the base class of the new class cannot directly select CToolbar, select CToolBarCtrl as the base class when selecting a new class, when the derived class is generated, then all CToolbarCtrl class names in the implementation are modified to CToolbar Control class, and use ClassWizard adds messages for new classes WM_Paint, WM_NCPAINT, WM_MOUSEMOVE, WM_LBUTTONDOWN, and WM_LBUTTONUP messages to implement various characteristics of the top-plane tool bars in the new class. At the same time, add the included file testtoolbar.h in mainfrm.cpp.

(2) Improve the derived class realization file testtoolbar.h Content Class Ctesttoolbar: Public CToolbar

{... // Other code

PUBLIC:

Ctesttoolbar ();

File: // New class constructor

UINT getColumns () {return m_ncolumns;}; // get column number

Void setState (uint NLEFT, BOOL NSTATED); / / Set the number of columns and status

Void OnDrawBorder (int index, cdc & dc, int flag); //

Void OneRaseBorder (int index, cdc & dc); // Remove the border

Void OnDrawBorders (); // Painting Flat Characteristics

Void OnDrawsep (INT INDEX, CDC & DC); / / Drawing

void ondrawgrapper (); // painting handle

... // Other code

#ifdef _Debug

File: // Increase Insert Control

Virtual void assertvalid () const;

Virtual Void Dump (CDumpContext & DC) Const;

#ENDIF

protected:

FILE: // Add member variables

Uint m_ncolumn;

FILE: / / Toolbar Button Column

UINT M_NFLAGS;

File: // Mouse button logo

INT M_NINDEX;

FILE: / / Press the button number

INT m_nflagl;

File: // Left button Press the sign

Uint m_nstated;

File: // Toolbar Status

CRECT RT;

File: // Close button rectangular area

... // Other code

}

(3) Improve the derived class realization file testtoolbar.cpp content

... // Other code

#define Toolleft 18

#define lbuttondown 1

#define lbuttonup 2

... // Other code

Ctesttoolbar :: ctesttoolbar ()

{

File: / / Initialization variables in the constructor

m_ncolumns = 0;

FILE: / / Toolbar Button Column

m_cxleftborder = 16;

File: // Left border

m_cxrightborder = 3;

File: // Right boundary

m_cytopborder = 3;

File: // Top Boundary

m_cybottomborder = 3; // bottom boundary

m_nflags = 0;

FILE: // Button flag member variable

M_NINDEX = 0xfff;

FILE: / / Press the button number

m_nflagl = 0;

File: // Left button Press the sign

m_nstated = true;

File: // Toolbar Status

}

... // Other code

#ifdef _debug // Insert code is perfect

Void ctesttoolbar :: assertvalid () const

{Ctoolbar :: assertvalid ();

Void Ctesttoolbar :: Dump (CDumpContext & DC) Const

{Ctoolbar :: dump (dc);

#ENDIF

File: // _ debug

... // Other code

Although there is more functions that need to be implemented, it is always a text device that acquires all regions of the customer area or window, establishes a collection of brush and drawing function, so it only gives a function of the draw button convex and concave edge line, other functions can be patterned achieve.

Void Ctesttoolbar :: OnDrawBorder (int index, cdc & dc, int flag)

{

File: // Painting button edge FLAG = 0 convex = 1 concave

CRECT RECT; GetItemRect (INDEX, & Re); // Get customer area

Rect.right -; Rect.bottom

CPEN * Oldpen;

Uint color1, color2;

IF (Flag == 0) {// color processing of two states

Color1 = color_btnhilight; // Button Height Color

Color2 = color_btnshadow;

File: // Button Shadow Color

} else {

Color1 = color_btnshadow;

Color2 = color_btnhilight;

}

CPEN PEN1 (PS_SOLID, 1, :: GetsysColor (color1));

CPEN PEN2 (PS_SOLID, 1, :: GetSysColor (color2));

Dc.selectStockObject (null_brush);

Oldpen = dc.selectObject (& Pen1);

Dc.moveto (Rect.right, Rect.top); // Draw button

Dc.LineTo (Rect.LINETO (RECT.LINETO);

Dc.LineTo (Rect.LINETO (Rect.Left, Rect.Bottom);

Dc.selectObject (& Pen2);

File: // Draw button

Dc.Moveto (Rect.right, Rect.top);

Dc.LineTo (Rect.right, Rect.Bottom);

Dc.LineTo (Rect.LINETO (Rect.Left, Rect.Bottom);

File: //dc.selectstockObject (Black_pen); // Draw button Black Line

File: //dc.moveto (Rect.right 1, Rect.top);

File: //dc.lineto (Rect.right 1, Rect.Bottom 1);

File: //dc.lineto (Rect.Left, Rect.Bottom 1);

Dc.selectObject (OldPen);

DeleteObject (Pen1);

DeleteObject (Pen2);

}

Void ctesttoolbar :: onDrawborders ()

{

File: // Implement a flat toolbar

CRECT RECT;

Cpoint pt;

GetCursorpos (& PT);

File: / / get the mouse pointer

ScreenToClient (& PT); / / Turn to Window Coordinates

Int index;

INT count = getCount (); // Total number of tool bars button

CClientDC DC (this);

File: // Window Customer Area

TBButton Button;

File: // Button data structure

Ctoolbarctrl & Toolbarctrl = gettoolbarctrl ();

OnDrawGrapper ();

File: // Painting handle

For (INDEX = 0; index

GetItemRect (Index, & Re); // get the button rectangular area

Rect.Top ; Rect.top ;

Toolbarctrl.getButton (Index, & Button); // get button information

IF (Button.fsState & (TBSTATE_CHECKED | TBSTATE_HIDEN))

CONTINUE;

IF (Button.fsStyle & TBStyle_sep) {// drawing

IF (m_nnew! = 0) OnDrawsep (INDEX, DC);

Else IF ((m_nIndex == index) ||

Button.fsState & TBState_pressed) {// Concave button OneraseBorder (INDEX, DC); // Remove button boundary

IF (Rect.ptinRect (PT)) OnDrawBorder (INDEX, DC, 1); // Painting the concave button

Else OnDrawborder (INDEX, DC, 0); // Picking

} else if (! Rect.ptinRect (Pt) || m_nflags == lbuttonup ||

! (Button.fsState & TbState_enabled)) {

OneRaseborder (INDEX, DC); // Remove button boundary

} else if (m_nflags! = lbuttondown) {// convex button

OneRaseborder (INDEX, DC); // Remove button boundary

IF (m_nflagl == 0) // Mouse Press to prevent re-emergence again

OnDrawborder (INDEX, DC, 0); // Painting button boundary

}

m_nflags = 0; // Press the post-movement to convex

}

ReleaseDC (& DC);

}

Void ctesttoolbar :: onpaint ()

{

File: // Improve the redraw button function

CToolBar :: onpaint ();

OnDrawBorders (); // Process all button boundaries

}

Void Ctesttoolbar :: ONLBUTTONDOWN (UINT NFLAGS, CPOINT POINT)

{

File: // Improve the left mouse button to press the function

m_nflags = lbuttondown; // Set the mouse button flag

m_nflagl = 1;

CToolbar :: ONLBUTTONDOWN (NFLAGS, POINT); // Runput function

Int index;

INT count = getCount (); // Total number of toolbar buttons

TBButton Button;

Ctoolbarctrl & Toolbarctrl = gettoolbarctrl ();

For (INDEX = 0; index

Toolbarctrl.getButton (Index, & Button); // get button information

IF (Button.fsState & TBState_Pressed) {

File: // Record Press the button number

M_NINDEX = INDEX;

}

}

}

Void Ctesttoolbar :: ONLBUTTONUP (uint nflags, cpoint point)

{

File: // Perfect mouse release function

m_nflags = lbuttonup; // Set the mouse button flag

m_nflagl = 0;

CToolbar :: ONLBUTTONUP (NFLAGS, POINT); // Runput function

CRECT RECT;

Cpoint pt;

GetCursorpos (& PT); // Take the cursor position

ScreenToClient (& PT); / / Turn to Window Coordinates

CclientDC DC (this); // Window Customer Area

if (m_nIndex! = 0xffffff) {// Judging the button to execute the function is still concave

GetItemRect (m_nIndex, & rece); // acquired a rectangular area

Rect.Top ; Rect.top ;

OneRaseBorder (M_NINDEX, DC); // Delete button boundary

IF (Rect.ptinRect (PT)) OnDrawBorder (M_NINDEX, DC, 1); // Painting the concave button

}

M_NINDEX = 0xfff;

}

Void Ctesttoolbar :: ONMOUSEMOVE (Uint Nflags, Cpoint Point)

{

File: // Improve mouse mobile function

CToolbar :: ONMOUSEMOVE (NFLAGS, POINT); INT INDEX;

INT count = getCount (); // Total number of toolbar buttons

CRECT RECT;

IF (nflags & mk_lbutton) m_nflagl = 1; / / Prevent re-emergence again

ELSE m_nflagl = 0;

OnDrawBorders (); // Draw all buttons

For (INDEX = 0; index

GetItemRect (INDEX, & Re);

Rect.Top ; Rect.top ;

IF (Rect.ptinRect (Point) && // Get the input focus during the movement

! (GetButtonStyle (INDEX) & TBBS_SEPARATOR)) {

SetCapture (); // Set the mouse input focus

Return;

}

}

IF (nflags & mk_lbutton) {// prevent removal of the input focus

SetCapture (); // Set the mouse input focus

m_nflagl = 1;

Return;

} else m_nflagl = 0;

Releasecapture ();

Return;

}

Void ctesttoolbar :: onncpaint ()

{

File: // Background Heavy Picture Function

CToolbar :: onncpaint ();

OnDrawGrapper ();

}

Void Ctesttoolbar :: SetState (uint NLEFT, BOOL NSTATED)

{

FILE: / / Status Settings Function

m_cxleftborder = NLEFT; // Left border

m_nStated = nStated;

File: // Toolbar Status

}

(4) Several descriptions of relevant parties

1 Draw Button Conc Convered Bide Line Function OnDrawBorder ()

The button in the normal toolbar has a black side line, making the button confusing in the flat tool strip, but this button is not beautiful, so the black edge portion should be omitted, and the system's API function getSyscolor function must be used to get The edge color so that the button edge line is also changed when the system changes color, and since the uneven button edge drawing is identical, but the color is reversed, the two can be implemented by this function;

2 drawn separation line function onDrawsep ()

When the drawing is separated, each button should be traveled to obtain the position of the separation line, and the customer area text description table can be implemented, only the two lines can be achieved;

3 painting handle function onDrawgripper ()

The text description table of the entire window should be used when painting the handle, because the customer area description table cannot draw lines in the window of the non-customer area, and must also determine if the button is arranged in many ways, draws horizontal or vertical according to different arrangements. Handle, but also to implement the button function, with the VC 5 and other interface toolbar functions, but also determine if the toolbar is a child window status to determine if the handle and close the button;

4 Delete button edge line function OneRaseBorder ()

The function is used to eliminate the button concave convex edge line of the system, so that the button has a planar effect, but also use the system's API function getSysColor function to obtain system colors to ensure that the system can change the button side line when the system changes the color;

5 implement a flat toolbar all function functions onDrawborders ()

In this function, it should be specifically pay special attention to the button separator determination, buttons, buttons, the left mouse button is pressed, the button concavity state is determined, the button edge of the delete system is determined and press the left mouse button and move the mouse button. Judgment, etc., and need to use the toolbar control to obtain references to the toolbar; 6 Toolbar Update Function Function ONPAINT ()

In this function, attention should be aware of the call to the original system update function function to implement the dynamic prompt and button icon display.

7 mouse left mock button Press the function function onlinetondown ()

In addition to call the original system mouse button, press the function function to implement the sending of the message, you need to set the left mouse button to press the flag and record the position of the button, so that the program correctly determines the concavity state of the button. ;

8 mouse left mock button release function function online onlbuttondown ()

In addition to call the original system mouse button to release the function function, you need to set the left mouse button release flag to the program correctly determine the concavo-convex state of the button, in addition to the redraw button The state of the recess is made when the button function is executed, and the button should be made exactly the same as the function of the toolbar button and other advanced applications;

⑨ mouse mobile function function onmousemove ()

In this function, the left mouse button should be recorded and the mouse input focus is set when the mouse is moved to the button, and the mouse input focus is set to ensure the normal raised state and mouse click in the mouse movement. After the button is controlled after the button status, if the mouse click button, the button is not released, the mouse is not released and the button is moved, and the button is reiled on the button, and these all control the mouse. The function of focus, and release the mouse input focus in time;

⑩ Background redraw and other functions onncpaint ()

The background redraw function is used to prevent one toolbar from being switched and displayed, and the handle and close button in another toolbar disappear, which in the mouse repeatedly double-click the toolbar non-customer area, another sorting toolbar The phenomenon will appear; additional function setState () is used to set the top boundary and status of the toolbar to adjust the client area and provide the drawing status for the painting handle and the shutdown button.

In addition, there is a mouse to move to the handle of the cursor and the closing button function, because the space is limited, interested readers can be implemented.

6.3.5 Toolboot Stop Location

6.3.5.1 Standard 6.3.5.2 Quasi-Tool Bar Stop Location

Tools CTOOLBAR is a derived class for control class CControlbar. The initial stop position whose display is determined by calling inherited functions ccontrolbar :: enabledocking (dWord dwstyle), its parameter DWSTYLE is used to specify the docking specific location, related to this article The style is as follows, the rest, please refer to the online help of VC5:

CBRS_ALIGN_TOP Tools Stop Popped at the top of the customer area

The CBRS_ALIGN_BOTTOM toolbar stops at the bottom of the customer area

The CBRS_ALIGN_LEFT toolbar stops on the left side of the customer area

The CBRS_ALIGN_RIGHT toolbar stops on the right side of the customer area

CBRS_ALIGN_ANY Tools Stop in any location in the customer area

Using the application wizard AppWizard generated application, its default docking position is CBRS_ALIGN_ANY, that is, it is allowed to stop any side of the customer area, and normal display is close to the top of the customer area: Enabledocking (CBRS_ALIGN_ANAY), see the toolbar of the above toolbar Function oncreate ().

The single document of the application and the multi-document window frame class is the derived class of CFrameWnd, which is implemented by calling inherited functions cframewnd :: enabledocking (dword dwdockstyle), which is optional In addition to the above five, the CBRS_FLOAT_MULTI parameter has also increased, which is mainly increasing to design a floating tool strip, which is used to determine that there are multiple floating toolbars that are allowed in a frame window. Also utilize the application wizard AppWizard generated application, the default docking position is also CBRS_ALIGN_ANY, that is, any side of the frame window, normal display is close to the top of the frame window, which is enabledocking (cbrs_align_any), see the above Toolbar establish function oncreate (). 6.3.5.3 Dock Position of Floating Tools

When there is a plurality of floating tools in a frame window, you need to use the function void dockcontrolbar (ccontrolbar * pbar, uint ndockbarid = 0, lpcRect LPRECT = NULL) to determine the toolbar to control the docking position, which is also a member function of the CFrameWnd class. The parameter PBAR is used to point to the toolbar object that is controlled, and the parameter NDOCKBARID is used to determine which edge of the toolbar is stopped on the frame window, and the value is:

AFX_IDW_DOCKBAR_TOP Tools Bars Top of the Frame Window

AFX_IDW_DOCKBAR_BOTTOM toolbar is stopped at the bottom of the frame window

AFX_IDW_DOCKBAR_LEFT Tools Stop The left side of the frame window

AFX_IDW_DOCKBAR_RIGHT toolbar is on the right side of the frame window

If the parameter ndockbarid is 0, the toolbar can stop on any of the parked edges in the frame window, the default location of the default position.

6.3.5.4 Toolbar connection stop method

In many applications, there is a case where multiple tools strips on a one-on-one edge of a window is stored. The above toolbar is used to control the LPRECT parameters of the function DockControlbar, and the rectangular area of ​​the control tool bar To achieve this feature, such as the function implemented by the author is as follows:

1 Add function definition in the main program implementation file mainfrm.h

PUBLIC:

Void DockControlbarleftof (CToolbar * Bar, CToolbar * Leftof);

2 Add the following functions in the main program implementation file mainfrm.cpp

Void CMAINFRAME :: DockControlbarleftof

CToolbar * Bar, CToolbar * Leftof)

{

File: // Set the toolbar to stop in the same side

CRECT RECT;

DWORD DW;

UINT N;

RECALCLAYOUT (); // Re-display

Leftof-> getWindowRect (& Re);

Rect.offsetRect (1,0); // Set offset value to stop in the same window

DW = leftof-> getbarstyle ();

n = 0;

n = (DW & CBRS_ALIGN_TOP)? AFX_IDW_DOCKBAR_TOP: N;

n = (DW & CBRS_ALIGN_BOTTOM && n == 0)? AFX_IDW_DOCKBAR_BOTTOM: N;

n = (DW & CBRS_ALIGN_LEFT && n == 0)? AFX_IDW_DOCKBAR_LEFT: N;

n = (dw & cbrs_align_right && n == 0)? AFX_IDW_DOCKBAR_RIGHT: N;

DockControlbar (Bar, N, & Re);

}

In this function, you should pay attention to the call to the recalclayout () function and the OFFSETRECT () function. The previous function is used to reset the adjusted client area and toolbar, and the latter function is used to re-determine the rectangular area, which is equivalent to using the mouse. Drag the second toolbar to the previous toolbar.

3 Modify the application establishment function on the corresponding DockControlbar () function in the oncreate () function is the DOCTCONTROLBAROF () function, and sets the toolbar pointer correctly, see the related functions in the toolbar's establishment skills.

6.3.5.5 Top stop control of custom tool bars

Another type of toolbar is a docking position of custom toolbar, such as a docking position with a general control function tool, which mainly implements the positional relationship between the left custom tool strip and the top toolbar. It is true that the method is as follows:

1 Open menu resources to add top position to control menu item IDD_DLGBARTOP;

2 Add member control variables m_bdialogtop in implementing files mainfrm.h;

BOOL M_BDIALOP;

And set the initial value for it in the constructor;

3 Use the class wizard function to set the response function for the menu item;

4 Improve the message mapping function in implementing file mainfrm.cpp.

Void CMAINFRAME :: OnButtondlgbartop ()

{

File: // Table Position Control Function

IF (m_bdialogtop) m_wnddlgbar.SetWindowPOS

& m_wndstatusbar, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);

File: // Other tool bars stop at the top, the toolbar is under

Else M_WnddlgBar.SetWindowPos (& WNDTOP, 0, 0, 0, 0,

SWP_NOSIZE | SWP_NOMOVE); / / Stop in the top

RECALCLAYOUT ();

File: // Re-display the window

m_bdialogtop =! m_bdialogtop; // change the variable logo

}

Void CMAINFRAME :: OnUpdateButtondlgbartop (ccmdui * pcmdui)

{

File: // Set the menu item check status

PCMDUI-> setCheck (m_bdialogtop);

}

6.3.6 Sort Method for Toolbar Button

With the application toolbar generated by the application wizard AppWizard, its buttons are arranged in a single line, which is neither aesthetically unattractive and practical in actual procedures, many of the tools in many large applications, multiple rows. Sort by, to implement this arrangement in its own application, should be controlled in derived classes as follows:

(1) Add function definition and member variable control in TestToolBar.h

Class Ctesttoolbar: Public CToolbar

{... // Other code

PUBLIC:

Ctesttoolbar ();

File: // Added a line after constructor

Void setColumns (uint ncolumn); // Add column control

... // Other code

protected:

FILE: // Add member variables

Uint m_ncolumn;

FILE: / / Tools Cap

... // Other code

}

(2) Add variable initialization and functions in TestToolBar.cpp

Ctesttoolbar :: ctesttoolbar ()

{

File: / / Initialization variables in the constructor

m_ncolumns = 0;

File: // Tools Press button column

... // Other code

}

Void Ctesttoolbar :: SetColumns (uint ncolumns)

{

File: // Set button arrangement

m_ncolumns = ncolumns; // Column number int ncount = gettOOLBARCTRL (). getButtonCount (); // The number of buttons

For (int i = 0; i

Uint nStyle = getButtonStyle (i); // button style

Bool BWRAP = (((i 1)% ncolumns == 0);

IF (bwrap) nStyle | = TBBS_WRAPPED; // Setting up

Else NStyle & = ~ TBBS_WRAPPED; // does not change

SetButtonStyle (i, nstyle); // Setting style

}

INVALIDATE (); // window update

GetParentFrame () -> RECALCLAYOUT (); // Toolbar Status Update

}

(3) Add a column control function for the corresponding toolbar on the application establishment function on, and pay attention to the column control parameter processing of the saving and recovery toolbar status function, see Toolbar establishing skills and status save and recovery The relevant functions, recompile and execute applications, you can see multi-line toolbars.

转载请注明原文地址:https://www.9cbs.com/read-22426.html

New Post(0)