VC small knowledge summary (continued)

xiaoxiao2021-03-06  37

1) When a document is modified, how to add a flag '*'? Overload the cDocument class with a virtual setmodifiedflag on the headline:

Void ctest2doc :: setModifiedflag (Bool Bmodified) {cstring start = gettitle (); cstring strdirtyflag = "*"; // Note Space Before the '*' // sowe don't break save as dialog

if (IsModified () && bModified!) {SetTitle (strTitle strDirtyFlag);} else if (! IsModified () && bModified) {int nTitleLength = strTitle.GetLength (); int nDirtyLength = strDirtyFlag.GetLength (); SetTitle (strTitle .Lex (NTILENGTH - NDIRTYLENGTH);

Updateframecounts ();

CDocument :: setmodifiedflag (bmodified);

(2) VC6.0 compatibility for VC5.0? Unfortunately, VC6.0 is not compatible with VC5.0 in debug mode, but there is no problem in the issuance mode. The reason is in Microsoft to change the format of the DLL used in debug mode, but retain Original file name. Therefore, do not open the debug version of VC5.0 in VC6.0.

(3) Print and printer problems? I touched such a problem: use the mm_lometric mode in the print method, change the size of the font in the logfont structure, but I don't know if 173 (or for the screen is 25) Where is it automatically. However, when I use another printer when it is not suitable. I want to know: How do I adjust this number to all prints.

I have also encountered a similar problem, I let the user change the font (size, color, etc.). These changes look very good on the screen, but when printing is too small (my colleague added a magnification in the package) The reason is very simple: the resolution of the printer may be 300dpi, and the resolution of the screen is much lower. I am so resolved: After getting the screen font information, I get the millimeter size of the screen font (using lptod, then The mode changed to mm tricic, call DPTOLP, then set the same mode to the printer, then call the LPTODP. After switching to the original mode, I called DPTOLP, which got the desired font height and width. In LogFont This value is used, and there are other font information such as underline, italics, and I realize the user's requirements.

(4) CRICHEDITCTRL Scroll Bob Problem? I use cricheditctrl control to display data in a file (set this control to read-only). I have set ES_MULTILINE | ES_AUTOVSCROLL, but when data content is more than control The scroll bar does not appear, is it caused other problems because of the read-only attributes?

ES_AUTOVSCROLL | ES_AUTOHSCROLL properties are only valid when control is editable. You can use the following scroll styles to make scroll bars: WS_VSCROLL | WS_HSCROLL, but so, no matter how big your data is, the scroll bar is always appear.

(5) Read more for 32K from the database? I met the problem when I read data from the database. When the data column contains more than 32K content, I can't read it, I tried odbc :: sqlgetdata () not .

Which type of database? MS SQL, SYBASE ... Try setting the size: BOOL CGETBLOBSTMT :: Execute (lpctstr stmt) {m_crute = 0; m_size = 0; lpbyte lpdata; lpdata = (lpbyte) Globalock (M_HDATA);

M_retcode = SQLSETSTMTOPTION (GetHandle (), SQL_MAX_LENGTH, M_DWBYTESLEFT);

m_retcode = SQLExecDirect (GetHandle (), (UCHAR *) stmt, SQL_NTS); if (m_retcode == SQL_SUCCESS) {m_retcode = SQLFetch (GetHandle ()); if (m_retcode == SQL_SUCCESS || m_retcode == SQL_SUCCESS_WITH_INFO) {m_retcode = SQLGetData (GetHandle (), 1, SQL_C_BINARY, lpData, 254, & m_cbSize); while (m_retcode == SQL_SUCCESS_WITH_INFO) {lpData = 254; m_retcode = SQLGetData (GetHandle (), 1, SQL_C_BINARY, lpData, 254, & m_cbSize);} GetError ();}} GlobalUnlock (m_hdata); # i i TestDataTRACE ("% ld", m_size); # ENDIF

Savefile ();

Return RetValue;}

(6) How to get characters in cricheditctrl? I want to use the right-click menu in cricheditctrl, so I want to determine the position of the character at the cursor.

View the following help: Iricheditolecallback :: getContextMenuem_setolecallback

(7) How to limit the size of the MDI sub-frame maximization? Instead of PrmaxSize with PTMaxTracksize, as shown below:

void CChildFrame :: OnGetMinMaxInfo (MINMAXINFO FAR * lpMMI) {// TOD Add your message handler code here and / or call default CChildFrame :: OnGetMinMaxInfo (lpMMI); lpMMI-> ptMaxTrackSize.x = 300; lpMMI-> ptMaxTrackSize.y = 400;

(8) How to switch the viewport without damaging them? I created an SDI application with a static partition, the work area is displayed on the left, and the thing that is selected on the left. I want to reach if it is between the partition Switch without overwriting or destroying the original CVIEW object.

The following code is what you want:

class CExSplitterWnd: public CSplitterWnd {// Constructionpublic: CExSplitterWnd (); // Overrides // ClassWizard generated virtual function overrides // {{AFX_VIRTUAL (CExSplitterWnd) //}} AFX_VIRTUAL // Implementation virtual ~ CExSplitterWnd (); BOOL AttachView (CWnd * pView, int row, int col); BOOL DetachView (int row, int col); // Generated message map functions // {{AFX_MSG (CExSplitterWnd) // NOTE - the ClassWizard will add and remove member functions here //. }}} AFX_MSG DECLARE_MESSAGE_MAP ()};

CEXSPLITTERWND :: CEXSPLITTERWND () {}

CEXSPLITTERWND :: ~ CEXSPLITTERWND () {}

BOOL CExSplitterWnd :: AttachView (CWnd * pView, int row, int col) {// Make sure the splitter window was created if {ASSERT (0) (IsWindow (m_hWnd)!); TRACE (_T ( "Create the splitter window before Attaching Windows to Panes "); Return (false);

// Make Sure The Row and Colone (Row> = GetRowcount () || col> = getColumnCount ()) {assert (0); Return False;}

// is the window to be attach a valid one if (pView == null || (! Iswindow (pView-> m_hwnd)) {assert (0); return false;}

PView-> setdlgctrlid (idfromrowcol (row, col)); pView-> setparent (this); pView-> showwindow (sw_show); pView-> UpdateWindow (); return (true);}

BOOL CExSplitterWnd :: DetachView (int row, int col) {// Make sure the splitter window was created if {ASSERT (0) (IsWindow (m_hWnd)!); TRACE (_T ( "Create the splitter window before attaching windows to panes ")); Return (false);

// Make Sure The Row and Colinger Are // Withnin Bounds IF (Row> = GetRowcount () || col> = getColumnCount ()) {assert (0); Return False;}

CWND * PWND = getPane (Row, Col); if (PWND == Null || (! Iswindow (pWnd-> m_hwnd)) {assert (0); returnaf false;}

PWND-> showwindow (sw_hide); PWND-> UpdateWindow ();

// set the Parent Window Handle To Null So That Thistroyed When THENT (Splitter) IS DESTROYED PWND-> setParent (null); Return (TRUE)

(9) Change the list of flashing phenomenon? I created a simple dialog and set a list control in the dialog box, which occupied all the clients of the dialog. The dialog box can change the size, so I want to ensure that the list control maintains the correct location in the dialog, I use movewindow () in the onsize () event of the dialog, which plays the role, but when the user changes the larger hours of the dialog, list controls Keep it. To solve this problem, use showWindow (sw_hide) to hide the list control with ShowWindow before using MoveWindow, and then display the list control with ShowWindow after MoveWindow.

(10) Handling a list of visible items? I have added a lot of items in a list control. I will handle it by getting an entry or lasting which entry is handled. I read the help of clistctrl :: GetItem () But did not find how to determine if an entry is visible.

If you just want to handle visible entries, you can use gettopIndex. It returns the index value of the maximum visible entry, then you can use getCountPage to get the number of entries in the visible area.

(11) What is the problem of generating threads? I have encountered problems when using CreateThread. I want to call the function and the called function belong to the same class, and the result is the following error when I call CreateThread:

Error C2440: 'Type Cast': Cannot Convert from 'unsigned long (__stdcall cdmi :: *) (void *)' to 'unsigned long (__stdcall *) (void *)'

Method 1: (1) 'unsigned long (__stdcall cdmi :: *) (void *) is a pointer to a member function of a CDMI. (2)' unsigned long (__stdcall *) (void *) 'is just a C Form function pointer. The compiler cannot convert (1) to (2) because the C member function takes the first (hidden) parameter "this pointer" as a member function, but is an exception to a static member. Solved as follows.

Class Xmythread {public: void startthread (void); Virtual uint threadfunction (viID); static uint __bogusthreadfunc (lpvoid lpparam);

Void Xmythread :: StartThread () {AFXBEGINTHREAD (__ bogusthreadfunc, this);}

Uint xmythread :: threadfunction (void) {// Here you do all your real work return 0;}

Uint xmythread :: __ bogusthreadfunc (lpvoid lpparam) {xmythread * this = Dynamic_cast (lpparam); returnction ();

For The Sake of Clairty, I Did Not Add Stopthread and I Did Not Save Thecwinthread * Returned by Afxbeginthread.

If You Wanted A Thread That Does Other Things, Simply Derive from xmythreadand override threadfunction ()

Example: class xanotherthread: public xmythread {virtual uint threadfunction (void);

Uint xanotherthread :: threadfunction (void) {// do some other Work Here Return 0;} Method 2: CDMI :: MonitorFiles () is a static member function.

(12) CFILE uses a buffer? Please tell me whether CFILE uses a buffer to handle the file?

CFILE does not use the I / O buffer routine of the run library. CFILE does not use buffers from this sense. However, it is possible that the operating system uses buffer when processing files. If you don't need buffers at all, you can set file_flag_no_buffering The only way to work in this mode is CFILE :: attach ().

(13) DAO password? I created an MFC application using the database. Use the class template to generate CDAORECORDSET to open the database (not ODBC), but how do I open a password-protected database?

Method 1: Try the following code:

DAODBENGINE * PDBENGINE = AFXDAOGETENGINE (); Assert (pdbengine! = Null);

Colevariant Varusername (strusername, vt_bst); Colevariant Varpassword (strpassword, vt_bstrt);

DAO_CHECK (pdbengine-> put_defaultuser); DAO_CHECK (PDBENGINE-> PUT_DEFAULTPASSWORD (V_BSTR (& Varpassword));

Method 2: You can open: MyDaodatabase-> Open ("c: /mydatabasefile.mdb", false, false, "; pwd = mypassword"); btw: Don't forget PWD = front; .

(14) How do you know when CListBox scroll? Every time you draw a list box, you have to reload a certain item, get DC color from the parent window through the message WM_CTLCOLOR. So the scrolling of each owed list box You can use WM_CTLCOLOR to verify whether it is scrolling.

HBRUSH CParentDlg :: OnCtlColor (CDC * pDC, CWnd * pWnd, UINT nCtlColor) {// is the control _the_ list box we're interested in? If (nCtlColor == CTLCOLOR_LISTBOX && pWnd-> GetDlgCtrlID () == IDC_LIST) { // if the top index change, The List Box Has Been Scrolled

INT ITOP = ((ClistBox *) PWND) -> gettopIndex ();

IF (ITOP! = m_itopold) {// Keeps TRACKING OF THE TOP INDEX CHANGES M_ITOPOLD = ITOP;

// process scrolling ...}}

Hbrush Hbr = CDIALOG :: ONCTLCOLOR (PDC, PWND, NCTLCOLOR); RETURN HBR;} Using this method can not have to generate an inheritance class in order to implement this function.

(15) How to deal with the inactivity of the viewport? Is there any way to make ClistView a style similar to a WM_DIASBLED or a background color.

Method One: you have to do is WM_SETFOCUS message processing CListView and then call SetFocus in the TreeView, so, ListView will never get the focus afx_msg void CMyListView :: OnSetFocus (CWnd * pOldWnd); {// assuming m_pwndTreeView points to. THE VALID TREEVIEW // on the left side m_pwndtreeview-> setfocus ();} method 2: Rebreload PretranslateMessage, then return true when the message is WM_LBUTTONDOWN or WM_RBUTTONDOWN.

(16) How to use ColeClientItem ID interface? I created a way to use the ColeClientItem object, I want to use its automation method. Is there a way to get the IDispatch interface? I tried the GetIDispatch function of ccmdtarget as base class but but Error, I have used Enableautomation and GetIDispatch, but I didn't get anything.

There is an article on this article (TN039) in MSDN. The following code may be what you need:

LPDISPATCH CMYCLIENTITEM :: getidispatch () {assert_valid (this); assert (m_lpobject! = Null);

LPunkNown LPUNK = M_LPOBJECT;

Run (); // must be running

LPOLELINK lpOleLink = NULL; if (m_lpObject-> QueryInterface (IID_IOleLink, (LPVOID FAR *) & lpOleLink) == NOERROR) {ASSERT (lpOleLink = NULL!); LpUnk = NULL;! If (lpOleLink-> GetBoundSource (& lpUnk) = NOERROR ) {Trace0 ("Warning: Link is not connection! / N"); lpolelink-> release (); return null;} assert (lpunk! = Null);

LPDISPATCH LPDISPATCH = NULL; IF (lpunk-> queryinterface (iid_idispatch, & lpdispatch! = Noerror) {trace0 ("Warning: does not support idispatch! / N"); return null;}

Assert (lpdispatch! = Null); return lpdispatch;}

(17) Regarding the user-defined message? I wrote a dialog box based on the MFC application. In this program, I created the thread waiting for the network to transfer data, once the thread received the data, it transmits a user Customized message to the dialog, making the dialog saying data over. But why can I capture the WM_MYCMD in CMYDIALOG:: PRETRANSLATEMESSAGE (MSG * PMSG), but can't be mapped with ONMYCOMMAND?

Set the base class of all custom messages to WM_APP instead of WM_USER.

(18) Exit when you open a document?

I have an MDI program. In the process of opening the file, I want to determine whether the document is a document that needs to be processed. Therefore, I detected whether a number in the document meets the requirements, how to appear when it is not the document An error message, then do not open this document? Set a flag to the document, if the document is not the desired, set it. Then on Onoplendocument is detected, when the discovery flag is set, return FALSE.

(19) Removal of multi-selection in the CListCtrl control?

How to delete multiple selections from CListCtrl?

Treated as follows: If your CListCtrl is M_List, to_Delete is a plurality of arrays .i = 3d0; position pos = 3dm_list.getfirstselectedItemPosition (); if (poS) While (POS) to_delete [i ] = 3dm_List.getNextSelectedItem (POS) The item is then saved in TO_DELETE with the item to be saved, using getSelectedCount to get the number of options.

(20) Login status of working thread?

I use a loop to delete a few instances of threads created by AFXBEGINTHREAD. Each thread opens an inet connection, opens a URL and returns the result. Which one I need to find out or when these threads go to the login state.

Handle according to the following method: (pseudo code)

// Start threads for (UNSigned u = 0; u M_HTHREAD;}

DWord count = Number_of_threadsdword dwWait;

While (count) {dwwait = :: WaitFormultiPleObjects (Count, ThreadHandleArray, False, Infinite);

if (dwWait> = WAIT_OBJECT_0 && dwWait <(WAIT_OBJECT_0 count)) {dwWait - = WAIT_OBJECT_0; // dwWait now has index to thread that completed do whateveryou want to do with it // set array back up for next wait if (dwWait ! = (count - 1)) ThreadHandleArray [dwwait] = threadhandleArray [count - 1]; count--;}}

(21) How do I increase the event handler of the ActiveX control in the view?

If I join Microsoft's web browser in the dialog, I can easily add the processing of the event through class template. But I now use m_pbrowser = new cwebbrowser2 in the view, how should I process the event?

Go to www.vcdj.com (INET chapter), there is an article named "Building a WebBrowser In A Afternoon". The following code may be what you need:

#include // for AFX_EVENT DEF.

Bool oncmdmsg (uint nid, int ncode, void * pextra, afx_cmdhandlerinfo * phandlerinfo) {AFX_EVENT * PEVENT = (AFX_EVENT *) PEXTRA;

// if this is a control notification event. If (ncode == cn_event) {// if we have information on this event. If (pevent) {// Event Dispid is stored at pevent-> m_dispid // Event Disprams Arend AT pevent-> m_pdispparams // handle the Event from here ...}} Return CWnd :: ONCMDMSG (NID, NCODE, PEXTRA, PHANDLERINFO);

(22) How to create a dynamic TREE control?

I want to create a dynamic Tree control, just like a pop-up window, but it is not as easy as imagination.

Method 1: Create a style of WS_POPUP, WS_CAPTION and WS_TICKFRAME with CreateWindow and as a parent window.

Method 2: Create a dialog containing the Tree control.

(23) Do not open the document when the SDI program begins?

I created an SDI application, but every time it opened a document ("Untitled"), how do you not let it open this document?

See if there is any call to the onfilenew in the initInstance function, remove it.

(24) What is the column selection in the List control?

I have troubles up when dealing with the List control, I want to create a listView to display the list of information in ListView and ReportView in ListView and ReportView according to the TREE control. The following is the relevant code:

// set full selectListView_sextendedListViewStyle (m_plstcustomers-> getsafehwnd (), lvs_ex_fullrowselect);

Handle as follows:

// --------------------------------------------- ------- bool CCommCtrlUtil32 :: ListCtrl_ModifyExtendedStyle (CListCtrl & p_rListCtrl, const DWORD p_dwStyleEx, const bool p_bAdd) {HWND t_hWnd = p_rListCtrl.GetSafeHwnd (); DWORD t_dwStyleEx = ListView_GetExtendedListViewStyle (t_hWnd);

if (p_bAdd) {if (0 == (p_dwStyleEx & t_dwStyleEx)) {// add style t_dwStyleEx | = p_dwStyleEx;}} else {if (! 0 = (p_dwStyleEx & t_dwStyleEx)) {// remove style t_dwStyleEx & = ~ p_dwstyleex;}}

Listview_sextendedListViewStyle (t_hwnd, t_dwstyleex);

Return True;}

(25) How to override the MRU file?

I created an application to load the image file, but when I clicked on the MRU file list under the File menu, I can't load the previously opened file. Below is the solution I can think of: (1 ) Define a member function (for example: cmydoc :: reopen) in the document class to handle this problem, indicate the parameters and return values. (2) Generate a CMULTIDEMPLATE inheritance class (such as CMYDOCTEMPLATE), define a constructor, take and the same base class parameters, do nothing, just call the constructor for the base class (3) overload MatchDocType:. CMyDocTemplate :: Confidence CMyDocTemplate :: MatchDocType (LPCTSTR lpszPath, CDocument * & rpDocMatch) {Confidence match = CMultiDocTemplate :: MatchDOCTYPE (LPSZPATH, RPDOCMATCH);

IF (YESALREADYOPEN == Match) // CLEAR ENOUGH {assert_kindof (CMYDOC, RPDocmatch); (CMYDoc *) RPDocmatch -> Reopen (/ * Your parameters * /);

// you can take any other actions here ...}

Return match;} When this function returns "YESALREADYOPEN", your document framework will be activated.

-------------------------------------------------- (26) The image of the cimagelist control is displayed as yellow?

I used a CIMAGELIST control to load bitmap, used for Tree control, and other colors are normal, orange is displayed as yellow.

You can only use the 20 colors specified by the system (orange not included); of course, you can also use the following method to load the graph resource without being limited by the number of colors.

HBITMAP LoadResourceBitmap (HINSTANCE hInstance, LPSTR lpString, HPALETTE FAR * lphPalette) {HRSRC hRsrc; HGLOBAL hGlobal; HBITMAP hBitmapFinal = NULL; LPBITMAPINFOHEADER lpbi; HDC hdc; int iNumColors; if (hInstance hRsrc = :: FindResource (, lpString, RT_BITMAP)) {hGlobal = :: LoadResource (hInstance, hRsrc); lpbi = (LPBITMAPINFOHEADER) LockResource (hGlobal); hdc = :: GetDC (NULL); * lphPalette = CreateDIBPalette ((LPBITMAPINFO) lpbi, & iNumColors); if (* lphPalette) { :: SelectPalette (hdc, * lphPalette, FALSE); :: (hdc) RealizePalette;} hBitmapFinal = :: CreateDIBitmap (hdc, (LPBITMAPINFOHEADER) lpbi, (LONG) CBM_INIT, (LPSTR) lpbi lpbi-> biSize iNumColors * Sizeof (RGBQUAD), (LPBitmapInfo); :: ReleaseDC (NULL, HDC); // :: unlockResource (hglobal); // :: freeeresource (hglobal);} return (hbitmapfinal);}

// internally used by LoadResourceBitmapHPALETTE CreateDIBPalette (LPBITMAPINFO lpbmi, LPINT lpiNumColors) {LPBITMAPINFOHEADER lpbi; LPLOGPALETTE lpPal; HANDLE hLogPal; HPALETTE hPal = NULL; int i; lpbi = (LPBITMAPINFOHEADER) lpbmi; if (lpbi-> biBitCount <= 8) * lpiNumColors = (1 << lpbi-> biBitCount); else * lpiNumColors = 0; // No palette needed for 24 BPP DIBif (lpbi-> biClrUsed> 0) * lpiNumColors = lpbi-> biClrUsed; // Use biClrUsedif (* lpiNumColors ) {hLogPal = GlobalAlloc (GHND, sizeof (LOGPALETTE) sizeof (PALETTEENTRY) * (* lpiNumColors)); lpPal = (LPLOGPALETTE) GlobalLock (hLogPal); lpPal-> palVersion = 0x300; lpPal-> palNumEntries = * lpiNumColors; for (i = 0; i <* lpinumcolors; i ) {lppal-> palpalent.pered = lpbmi-> bmicolors.rgbred; lppal-> palpalent.pegreen = lpbmi-> bmicolors.RGBGreen; lppal-> palpalent.peblue = lpbmi- > Bmicolors.RgbBlue; if (i <= 10 || i> = 246) lppal-> palpalent.peflags = pc_nocollapse; else lppal-> palpalent.peflags = 0;} hpal = creagettt e (lppal); globalunlock (hlogpal); globalfree (hlogpal);} Return HPAL;} This function also overloads the bitmap palette, this function is ignored by cbitmap :: loadbitmap (it is only 20 kinds of only 20 Color). Therefore, to ensure that SELECTPALETTE and REALIZEPALETTE. (27) cannot correctly change the icon of the application correctly in the DC.

I have a dialog-based application. When I initialize, I use AFXGetApp () -> Loadicon (IDi_briefcase) to load their own icon, when copying the program to the desktop, the icon is what I expect. But I am The icon in the resource manager is still an icon of the MFC.

The resource manager uses only the 16x16 small icon, which may only modify the 32x32 standard icon in the resource editor. You need to rebuild 16x16 small icons.

(28) What is the problem of tool strip?

In the application I created three toolbars, I would like to let them arrange a line when the application is started, how do I do it under the main menu?

There is an example on the VC CDS:

INT CMAINFRAME :: OnCreate (lpcreatestruct lpcreatestruct) {// Other stuff here ...

Enabledocking (CBRS_ALIGN_ANY);

DockControlbar (& M_WNDTOOLBAR, AFX_IDW_DOCKBAR_TOP); DockControlbarleftof (& M_WndListToolbar, & M_WndToolbar); Return 0;}

Void CMAINFRAME :: DockControlbarleftof (ctoolbar * bar, ctoolbar * leftof) {create rect; dWord dw; uint n;

// get MFC to adjust the dimensions of all docked ToolBars // so that GetWindowRect will be accurate RecalcLayout (); LeftOf-> GetWindowRect (& rect); rect.OffsetRect (1,0); 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;

// When we take the default parameters on rect, DockControlBar will dock // each Toolbar on a seperate line. By calculating a rectangle, we in effect // are simulating a Toolbar being dragged to that location and docked. DockControlBar (Bar, n & RECT);

(29) Use the Active control in the SDI application?

I just learned how to use Active controls in the MFC application, and the documentation says you can only use when the view is CFormView and CDIALOG, but what should I do if other?

You can use the Active control anywhere in your application, not just CFormView and CDIALOG for the view base class. DevStudio is easier to use Active controls under these two conditions by resource editor and dialog templates. So, you can also use the Active control in any view, the condition is that you directly manipulate the control, create it and manually arrange it (this is also devstudio for what you do).

(30) The dialog box with the richedit control cannot be displayed normally?

I placed a RicheDit control in the dialog, but the dialog fails to display normally.

Calls in your application inInstance () :: afXINITRICHEDIT ()?

(31) Template member functions in DLL?

In a DLL, I use the template member function in the class you created in place instead of the pre-processed macro. But the following error appears:

Error C2664: 'Double Data :: Extract (Double &): Cannot CONVERT Parameter 1 from' Class Carray 'to' Double & 'Why do you look for a Double parameter when matching templates?

I think you may be a problem when expressing member functions (inline), please refer to the example below:

class AFX_EXT_CLASS Data: public CObject // This is not a template {public: Data (); Data (BYTE * buffer, int size); template Data (const CArray & array); template CArray & extract (CArray & array) {CArchive ar (& buffer Carchive :: store); ar >> array;}; double extract (Double &); (...) Private: cmemfile buffer;} (32) CFORMVIEW context help?

I want to join the real context help in the SDI application based on the CFormView class, but there is no success.

You should overload the onhelphittest function of the CMYFORMVIEW class:

Lresult CMYFORMVIEW :: OnHelphittest (WPARAM, LPARAM LPARAM) {LRESULT LRESULT = (LRESULT) 0X00;

CWND * PWNDCHILD = CHILDWINDOWFROMPOINT (CPOINT (LPARAM), CWP_ALL | CWP_SKIPInvisible);

IF (PWNDCHILD && :: Iswindow) {LRESULT = :: getWindowlong (pWNDCHILD-> M_HWND, GWL_ID);

IF (LRESULT) LRESULT = HID_BASE_COMMAND;

IF (LRESULT == (LRESULT) 0x00) LRESULT = :: getWindowlong (M_HWND, GWL_ID) HID_BASE_RESOURCE

return lResult;} Then you can use the help files usually use, but you want to ensure the correct prefix, please refer to TN028: Context-Sensitive Help Support For example: ID_SOME_MENU_ITEM_OR_COMMAND_BUTTONIDR_SOME_WINDOW_OR_DIALOGIDP_PROMPTIDW_CONTROL_THAT_IS_NOT_A_COMAND_BUTTON you have to confirm ID of the control you use is included in the. Document resource.hm.

(33) WriteObject function problem of CARCHIVE class?

Who knows how to avoid writing class names when using the WriteObject function of the CARCHIVE class?

The WriteObject function not only writes the class name, but also writes PID (see TN02), if you only want to write a text file, and you also want to use serialization, you can use the file pointer (with getfile) to store String. Or, you can use the CFILE class to handle this problem. If you are a text file, you can also use the CSTDIOFILE class.

(34) How to deal with BroadcastsystemMessage in RegisterWindowMessage?

I want to use BroadcastsystemMessage to communicate between two processes, I sent a message that was registered with RegisterWindowMessage from a process, but did not receive the message in the destination process.

I think you should register the message in the top highest window of the two processes. Look down:

static UINT sBroadcastCommand = :: RegisterWindowMessage (_T ( "BroadcastCommand")); BEGIN_MESSAGE_MAP (Gui_Top_Level_MainFrame, Gui_MainFrame) ON_REGISTERED_MESSAGE (sBroadcastCommand, onBroadcastCommand) END_MESSAGE_MAP ()

LRESULT GUI_MAINFRAME :: OnBroadcastCommand (uint amsg, lparam lparam) {Your code ...} and then send it to include: while the sending process 10: WHILE

Static uint sbroadcastCommand = :: registerWindowMessage ("BroadcastCommand");

Void SomeClass :: SomeMethod (void) {:: PostMessage ((hwnd) hwnd_broadcast, sbroadcastCommand, 0, YourMessageId;

(35) How to get notifications when selecting changes in CListCtr?

I used a CListCtrl in the Report View, I want to know when the selection has changed.

When selecting changes, you can use the button to be valid or invalid, follow the following:

Join the LVN_ItemChanged message processing .void cyorclassnamehere :: onItemChangeDeventList (NmHDR * pnmhdr, lresult * pRESULT) {nm_listview * pnmlistview = (nm_listview *) pnmhdr; * pResult = 0;

IF (pnmlistview-> uchanged == lvif_state) {if (pnmlistview-> unewstate getDLGITEM (idc_delete) -> enableWindow (TRUE); else getdlgitem (IDC_DELETE) -> EnableWindow (false);}}

(36) How to transfer an array to the ATL-COM object?

I want to create a function to transmit an array to the ATL-COM object.

The method of the following code is used in ActiveX, which may also be inspired by ATL-COM.

CoInitialize (NULL); CLSID m_clsid; USES_CONVERSION; :: CLSIDFromString (T2OLE ( "ROUNDANALOG.RoundAnlgAARCtrl.1"), & m_clsid); IDispatch FAR * pObj = (IDispatch FAR *) NULL; CString str = "UpdateControl"; BSTR bstr = Str.allocsysString (); HRESULT HR = CocreateInstance (m_clsid, null, clsctx_all, iid_idispatch, (void **) & pobj);

SafearrayAccessData (PSA, (void **) & bstrarray); bstrarray [0] = str.allocsystring (); bstrarray [1] = str.allocsystring (); SafearRayunAccessData (PSA);

Variantarg * pvars = new variantarg [1]; variantinit (& pvars [0]); pvars [0] .vt = vt_array | vt_byref | vt_bstr; pvars [0] .pparray = & PSA; Dispid Dispid; hr = pobj-> getidsofnames IID_NULL, & BSTR, 1, LOCALE_USER_DEFAULT, & DISPID;

DISPPARAMS disp = {pvars, & dispid, 1,1}; hr = pObj-> Invoke (dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_PROPERTYPUT, & disp, NULL, NULL, NULL); delete [] pvars; pObj-> Release (); CoUninitialize ();

Established the following and variable reference in your control:

Void crossanlgaarctrl :: savefunc (const variant far) {// Tod add your dispatch handler code hereassert (var.vt == vt_array | vt_byref | vt_bstr); SafeArray * psa = * var.ppArray;}

(37) How do I choose the node text in CTREECTRL to edit?

After adding an item to CTreeCtrl, what method can I edit the text of the node?

First set your ccomptreeCtrl with TVS_EDITLABELS properties. Use control properties when designing the control property to set with the getStyle () / setStyle () member function. Then please see the following code:

HtreeItem ccomptreectrl :: addset () {static int setcnt = 3d 1; htreeItem HITEM; CSTRING CSSET

// Create Text for New Note: New Set 1, New Set 2 ... CSSet.Format (_T ("New Set% D"), setcnt );

HITEM = 3D INSERTITEM (CSSet, IMG_ClosedFolder, IMG_CloseDfolder);

IF (HITEM! = 3D NULL) Editlabel (HITEM);

Return Hitem;}

(38) How to change the default cursor shape?

I tried to change the cursor to other shapes and colors, but did not change.

In the dialog box / window / you need to add processing on the WM_SETCURSOR message.

BOOL MyDialog :: OnSetCursor (CWnd * pWnd, UINT nHitTest, UINT message) {// TOD Add your message handler code here and / or call default :: SetCursor (AfxGetApp () -> LoadCursor (IDC_MYCURSOR)); return TRUE; / / RETURN CDIALOG :: OnsetCursor (PWND, NHittest, Message);} You have no success because the window cursor style cannot be NULL.

(39) How to use the keyboard to scroll through the vision?

My question is when I scroll by the mouse, the viewport scrolling is normal, but when using the keyboard, there is no happening.

Add the following two functions in your view inherit class, assume that the class is CScrollerView:

void CScrollerView :: OnKeyDown (UINT nChar, UINT nRepCnt, UINT nFlags) {BOOL processed; for (unsigned int i = 0; i

(40) How to handle the status bar in the thread?

In my application CWnd, there is a pointer pointing to the status bar, using pstatusbar-> setPaNText (0, status, true) to display some text is normal. But calling the function in the second thread is not , HWND warning.

When you send a CWnd pointer to another thread, m_hwnd will be empty. My way is to use PostthReadMessage to transfer the parent class of the message to the status bar, let it process the status bar.

(41) How to prevent Windows from shutting down?

I have an application to keep working. When the program runs normally, how to avoid the user turned off the system? Is it useless to use WM_QueryEndSession. Yes, use it in your main frame window.

// in the class headerafx_msg Bool ONQUERYENDSESSION (WPARAM WRESERVED, LPARAM Lendreason);

// in the message mappon_message (wm_queryendsession, onqueryndsession)

// in the class bodybool cmainframe :: ONQUERYENDSESSION (WPARAM WRESERVED, LPARAM Lendreason) {ix (lendreason = 3d = 3D endsession_logoff) {// user is logging off else // windows is going down

Return (bcanexit);

(42) How to make a button disable?

I use the following code to disable a button for id_button, why didn't change. Getdlgitem (IDC_Button) -> EnableWindow (false);

The EnableWindow function in the CWND class is used to enable or Disable a window class, because the CBUTTON class inherits to class CWnd, so you can use a button .Nable A window-based object can be followed:

PWND-> EnableWindow (TRUE); Disable an object available

PWnd-> EnableWindow (false); where PWND is a pointer VC pointing to the window object. The message WM_ENABLE tells the window that it is disable or enable, but it does not make one window enable or disable.

(43) How to display a dialog in the MFC extended dynamic link library (DLL)?

I have tried a dialog in the function defined in the DLL in the past few days, but I have already defined a dialog resource in the DLL. When the regular DLL is called, I can display it normally, why is it extension DLL? I can't display the same resources.

When you use resources in the DLL, some small details require attention, first, in the DLL run, you must save the DLL instance, you can pass by AfxiniteXtensionModule.

Static AFX_EXTENSION_MODULE EXTENSIONDLL;

extern "C" int APIENTRY DllMain (HINSTANCE hInstance, DWORD dwReason, LPVOID) {if (dwReason == DLL_PROCESS_ATTACH) {// Extension DLL one-time initialization if (AfxInitExtensionModule (extensionDLL, hInstance)!) return false;}

Return (TRUE);} then, each time you use a DLL resource, you must change the handle of the resource to point to the DLL, and save the resource of EXE, so that you will be properly recovered later.

void get_DLL_resource (void) {/ * this function changes the resource handle to that of the DLL * / // This function changes the resource handle to point DLL if (resource_counter == 0) {save_hInstance = AfxGetResourceHandle (); AfxSetResourceHandle (extensionDLL. hmodule);

Resource_counter ;} Next you need other functions to restore resource handles void reset_dll_resource (void) {/ * this function rest, resource handle set by'get_dll_Resource () '* /

IF (resource_counter> 0) resource_counter--;

If (resource_counter == 0) AFXSetResourceHandle (Save_HINSTANCE);} Next, it is very important, as long as it is possible to resume the resource handle, you will encounter a lot of problems. The reason is that the executable must be heavy and otherwise For example, if the user moves the DLL dialog, if the resource handle still has the resource of the DLL, the program crashed, I found it to restore the handle of the handle in the dialog box on LinitDialog (), the template of the dialog, etc. I have read it.

(44) What should I do if I want to hide the user interface?

I have compact and fun tools when the user uses it when I use it, I don't want it to display any user interface. Listening to everyone can be closed.

You can register a new window type, which has any properties except for the WS_Visble property, similar to CFrameWnd, implemented in the PrecreateWindow method. In addition, you can implement the m_ncmdshow to sw_hide in the oncreate method, the specific method is as follows:

INT CMAINFRAME :: OnCreate (lpcreatestruct lpcreatestruct) {if (cframewnd :: oncreate (lpcreatestruct) == -1) Return -1;

// hide ou app AFXGetApp () -> m_ncmdshow = sw_hide;

Return 0;}

(45) How to achieve the conversion of SDI and MDI?

I want to convert a composed SDI application to MDI, which is clearly more changes.

You can do this: create a class inherited in cmdichidwnd, not to prevent it to cchldfrm. Changed in cwinapp.

InitInstance () {. ... // instead of adding CSingleDocTemplate // Add CMultiDocTemplate. PDocTemplate = new CMultiDocTemplate (IDR_MAINFRAME, RUNTIME_CLASS (CSDIDoc), RUNTIME_CLASS (CChldFrm), // For Main MDI Frame change this frame window from // CFrameWnd derivative (ie CMainFrame) // to your CMDIChildWnd derived CChldFrm RUNTIME_CLASS (CSDIView));.. /// After this it is required to create the main frame window // which will contain all the child windows Now this window is // what . was initially frame window for SDI CMainFrame * pMainFrame = new CMainFrame; (! pMainFrame-> LoadFrame (IDR_MAINFRAME)) if return FALSE; m_pMainWnd = pMainFrame; .....} after the inheritance from the class CMainFrame CMDIFrameWnd replaced CFramWnd, All classes will inherit from cmdiframe instead of cframeWnd, you will find that the program has changed from SDI to MDI after compiling. Note: The constructor must be changed from private from private to public. Otherwise it will be wrong. (46) Vertical text in the CDC?

In the onDraw member function I want to make the text vertically, but the CDC does not support this process.

Method 1: If your vertical alignment refers to the text, the following code will help you: This code checks for a check box control, check whether the text needs to rotate.

// m_pcfytitle is a cfont * to the successd .// m_btotateytitle is a bool (== true if rotated)

Void cpage1 :: onrotateytitle () {logfont lgf; m_pcfytitle-> getlogfont (& lgf); m_brotateytitle = ((cbutton *) getdlgitem (IDC_ROTATEYTITETETE) -> getCheck ()> 0;

// escapement is reckoned clockwise in 1 / 10ths of a degree: lgf.lfescapement = - (m_brotateytitle * 900); m_pcfytitle-> deleteObject ();

m_pcfytitle-> CreateFontIndirect (& lgf); DrawSampleChart (); Note If you choose different fonts from cfontialog, you should set your LFScapeCapeMent members yourself. Transmit the LFESCAPEMENT values ​​after initialization to CFONTDIALOG.

Method 2: There is also a code for reference:

Logfont Locallogfont;

STRCPY (Locallogfont.LffAcName, Typeface);

LocalLogFont.lfWeight = fWeight; LocalLogFont.lfEscapement = Orient; LocalLogFont.lfOrientation = Orient; if (MyFont.CreateFontIndirect (& LocalLogFont)) {cMyOldFont = cdc-> SelectObject (& MyFont);}

(47) How to activate the grayed pop-up menu?

Set the menu item that is grayed when the design menu is running, how do you activate it at runtime?

Please see the sample code below:

Void CMYVIEW :: OnRButtondown (uint nflags, cpoint point) {cscrollview :: OnRButtondown (nflags, point);

CMenu * Menu, * popup; menu = new cmenu ();

// load menu from resource filemenu-> loadingMenu; popup = menu-> getSubmenu (0); // Item 0 is Dummy

Uint Nenable; Nenable = MF_BYCOMMAND | MF_GRAYED;

IF (Your Test) {Nenable = MF_BYCOMMAND | MF_ENABLED;

Popup-> EnableMenuItem (ID_Your_ID, Nenable);

// Display menuclienttoscreen (& points); popup-> TRACKPOPUPMENU (TPM_LEFTALIGN | TPM_RightButton, Point.x, Point.y, this); delete menu;

(48) Thread message?

How to transfer messages between threads correctly?

The following code will help you:

Void Cthread :: Onuseropen (WPARM WPARM, LPARM LPARM) {UNUSED (WPARM); AFXMESSAGEBOX ("User Open", MB_OK | MB_ICONEXCLAMATION);}

Of course, don't forget the following statement:

Class Cthread: Public CTHREAD: PUBLIC CWINTHREAD {Declare_DyncReate (CTHREAD) protected: cthread (); // protected confuctor used by Dynamic Creation AFX_MSG Void OnuserOpen (WPARM WPARM, LPARM LPARM);

(49) TreeCtrl control is too slow?

I inherited a Tree Control from CTreeCtrl. The overload is mainly to rewrite the text of each node. I wrote some code in the onpaint function, but it severely affects the TREE control scrolling speed.

OnPaint Function 1. Visible nodes, for GetFirstvisibleITEM and GetNextVisibleItem, is: a. Root node; b. Parent node has expanded node; therefore, "visible" means "not unfolded parent node hidden". When scrolling outside the customer, it is still visible to the above two functions.

2. When the content of Tree changes, it will only be re-painted by default. In addition, other nodes have no need to redraw, Tree is just scrolling the bitmap of DC. Don't draw you above. The node that needs to be seen will result in a reduction in speed. It is recommended that the test node rectangle is in the client area, so that only the nodes need to draw will be drawn .void cindenttree :: onpaint () {CPAINTDC DC (this); // device context For painting

HtreeItem HITEM = NULL; DRAWITEMSTRUCT DIS; CRECT RC;

// Redraw Only Visible Items with Indentation for (HITEM = GetFirstvisibleITEM (); HITEM; HITEM = GetNextVisibleItem (HITEM)) {IF (! GetItem, RC, FALSE) Continue;

IF (rc.top <= dc.m_ps.rcpaint.bottom && rc.bittom> dc.m_ps.rcpaint.top && = 20 rc.left <= dc.m_ps.rcpaint.right && rg.right> DC.M_PS. Rcpaint.LEFT) {Dis.hwndItem = (hwnd) HITEM; Dis.rcitem = RC; OnDrawItem (0, & DIS, & DC);}}}} OnDrawItem function 1. Deleted the following code:

ImageInfo * Pinfo = new imageinfo; ... delete pinfo; no need to use dynamic imageinfo variables, you can define it as stack variables. 2. GetItemState and GetItemText are GetItem, so you just call once, just You can get all the information you want from the node.

(50) About the toolbar?

I need to make a FLAT toolbar in the program, so I added a variable m_wndtoolbar. Modify the toolbar status (0, TBStyle_FLAT) in the oncreate () function of the program main window. Why run normal in NT, why is the toolbar in 95 Be transparent?

Some small bugs in the old version in ComctL32.dll, you can bring some questions when painting, you can use some custom code, there is downloaded on www.codeguru.com site, if you are using a version 6.0, you can also Use the following code (picking yourself mainfrm.cpp file)

m_wndToolBar.CreateEx (this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC); ModifyStyle replaced with the same size CreateEx toolbar somewhat different ((CreateEx built slightly smaller), try, if You still have this problem, check the version of ComctL32.dll Use the standard button to replace the FLAT.

(51) About thread message?

It's true, the onuseropen () function and the onuseropen (wparam, lparam) function are not a function, and the compiler when I check ONUSEROPEN (WPARAM, LPARAM), I won't call onuseropen What is wrong with what is the message image?

In fact, this is a strict manifestation of MFC, and when the function pointer is called, the pointer is determined by the incident. If the handle is not defined correctly, the call is of course illegal.

(52) About the focus of the control?

Who can give me an effective way: How to manage the focus of the dialog in the correct control when a control loses the focus.

I have a running program to achieve, not necessarily, but I can work.

Const int WM_VALIDATE_PARAMS WM_APP 101;

Void cMydlg :: ONKILLFOCUSNAME () {PostMessage (WM_VALIDATE_PARAMS, ED_NAME, 0L);

void CMyDlg :: OnKillfocusAddress () {PostMessage (WM_VALIDATE_PARAMS, ED_ADDRESS, 0L);} bool CMyDlg :: OnValidateParams (WPARAM rcId, LPARAM) {switch (rcId) {case ED_NAME: if (! validateName ()) m_edName.SetFocus () ;

Case ed_address: if (! ValidateAddress ()) m_edaddress.setfocus (); Break;

DEFAULT: BREAK;

Return True;} The above code can use the TAB key or mouse manipulation, use the focus to jump to the next control. When you want a control or reset, it will be some problems, especially in the KillFocus event.

(53) How to capture keyboard buttons?

How to capture an Alt 0 combination key in the sub-dialog of CTABCTRL

Keyboard messages can be intercepted in PretranslateMessage.

(54) How to achieve 3D effect?

How to implement the 3D effect of the EDIT and ListBoxes controls in the dialog? (Environment 95 / NT VC5.0)

1). Use the WS_EX_CLIENTEDGE logo to replace: CREATEWINDOWEX :: CREATEWINDOW or replace CWnd :: CreateEx with CWnd :: CreateEx). After the control is created, call ModifyStyleex (0, WS_EX_CLIENTEDGE).

(55) How to build a customer CSocket?

I have a customer socket to create a local connection in Socket. I use the following order:

CSocket * m_pSocket; m_pSocket = new CSMSSocket (this); m_pSocket-> Create (); m_pSocket-> Bind (m_intHostPort, m_strHostIPAddress); m_pSocket-> Connect (lpszAddress, nPort); but each time Windows Socket is directed to the other port How can I oriented to the same port (environment: 95 / NT VC5.0).

1). If you want to use the client socket, you can't call bind () before connect (), because the local port address is set by TCP / IP, we can't know the next time, I think we don't have to This does. 2). Look at the help of create (), tell us that we must specify a port value to create (), the default situation is 0, that is, the Window chooses a port for us to pass Create () will Automatic bundle. 3). I don't think you should do all work, but I want to always use an identical port to connect to the remote machine is an incorrect idea. Question out the port number / address combination must be unique, if you want In Create () refers to a fixed port number, you can only build a single connection with the remote machine. In the code you have written, the number of local port numbers can be changed, and multiple connections can be opened to achieve the same address. Listening Socket has many reasons to use a fixed port, but in connection (I don't think too much in Connecting Socket.

(56) DISABLE Customer Area of ​​Non-Modular Dialogs?

I have a non-modal dialog box in OCX (Object Connection, and Embed Customer Control Programs. It has a menu and toolbar. Now I want the Disable client area (just customer area, for example: set a waiting cursor when setting special variables, All controls in the area cannot be handled), but all controls in the client area should look at all changes (not disable)

You can try this way, create a sub-window, override all the user areas of the dialog, use the WS_EX_TRANSPAPApen transparent type, then call the function enableWindow (false), use setClasslong or other methods, call "Busy" cursor in the sub-window, this time The standard is correct, but the menu in the dialog box can also be used normally. (Let that it is to create a transparent sub-window to cover all the user area, then the disable of the transparent window, set the cursor "busy" in this window) I have not tried this method, but this method is introduced in some old Windows books. (57) About using setclasslong and setcapture problems

I have encountered some problems when I use the setClasslong Setup dialog cursor. When I use setcapture to capture my mouse,

When the cursor shape is not changed, the following is the original code:

Void cmousemovesimdlg :: ONLBUTTONDOWN (UINT NFLAGS, CPOINT) {MyDragging = true;

MyHPREVCURSOR = (hcursor) setClasslong (m_hwnd, gcl_hcursor, (long) loadcursor (), makeintresource (IDC_selectcursor));

SetCapture (m_hwnd); cdialog :: ONLBUTTONDOWN (NFLAGS, POINT);} If you remove SetCapture this line, the cursor will set correctly, but it can't capture the mouse message correctly. There is a problem (environment NT4.0 VC6 .0)?

1). If I don't make a mistake, setClasslong only affects the created window after calling it. You can use SetWindowl to change the properties of the existing window. (Why do I use setClasslong to change the cursor shape, why not replace it in the message WM_SETCURSOR. ) 2). I don't know the problem there, but the following method can overcome the issues brought by SetCapture, which is proposed from my program:

Void Cscribbleview :: ONLBUTTONDOWN (UINT NFLAGS, CPOINT) {....... setcapture (); // Capture The Mouse Until Button Up

MyHPREVCURSOR = (hcursor) setClasslong (m_hwnd, gcl_hcursor,

(long) loadcursor (AfxGetInstanceHandle (), makeintResource (IDC_CURSOR1)))));

SetCursor (AFXGetInstanceHandle (), makeintResource (IDC_CURSOR1))); ........

void CScribbleView :: OnLButtonUp (UINT nFlags, CPoint point) {if (! GetCapture () = this) return; ........ ReleaseCapture (); SetClassLong (m_hWnd, GCL_HCURSOR, (long) myhPrevCursor); return; }

(58) Animation control?

I use an animation control in the dialog, usually I use the CANIMATED OPEN member function, and add AVI's file name to use animation controls, how to join an AVI file in the resource file, use it as a resource?

1). Simple, introduce the AVI file into the resource, according to your favorite, it belongs to the type, replacing the name of the file by ID, so you can use .2). Click Right click in the resource window In the pop-up menu, select "IMPORT". This time opens the file selection box, select the desired file, then the system will ask the custom resource type, enter avi. An Avis resource group will be created, you selected The AVI file will appear in this group and have an ID.3). Manually add an AVI resource instructions in the resource file, such as: // In this hand-editing resource file idR_animation avi res / animate.avi (59) error Declare message?

I gave a message to send a message pView-> sendMessage (my_message, wparam, lparam); message declaration is considered an incorrect afx_msg void onmyMessage (); master, this is a command error declaration, the correct statement It should be: AFX_MSG LERSULT ONMYMESSAGE (WPAPRAM WPARAM, LPARAM LPARAM);

Because I don't use the parameters, the program work is also very good, so I don't know why there will be such a mistake. There is no error in the process after processing. But now there is a strange phenomenon in the Release version (Debug version No) The program will be non-normal, which is usually the phenomenon after sendMessage () returns. why?

1. I believe that the problem is on the wrong stack, "thiscall" should clear the stack after calling, the caller is pressed into the stack when the caller is called, but the parameters are not cleared. If you really don't need WPARAM, LPARAM If you don't need to return value, you can use the on_message_void message declaration. Definition in AFXPriv.h, is non-document, meaning it does not have any tips or possible interrupt programs, and you need to pay attention to thread messages, pay attention to thread messages It is variable, they will return Void, no LRESULT, the same statement .2. If you don't use WPARAM and LPARAM, why not define a user function to handle yourself?

(59) How to simulate the mouse action?

This is a problem that plagues me, how can I achieve the action of analog mouse, that is to make a program to implement the mouse click, double click, drag and other functions. I think I have to achieve corresponding messaging, but each time Unsuccessful. For example, I want to turn off the notepad window, can transfer WM_LBUTTONDOWN and WM_LBUTTONUP (X, Y value to close the point in the upper right corner of the notepad) to the Notepad window, but the window is not closed. Of course, I also know Close a window can be implemented by transmitting wm_quit or wm_close, why is the message of the mouse will be lost? Do you ask you how to simulate the action of the mouse, or give me some advice to close the window (not WM_CLOSE or WM_QUIT)

1). Try Window Hooks, you can use SETWINDOWSHOKEX and Journalplayback to handle mouse events. 2). You can use SendInput () in your document, which enables analog keyboard or mouse event. If you use NT, it can also be used Old function like mouse_event (), keyb_event, etc., in Win98, Sendinput () can be used as .3). Sorry, I can't give you a satisfactory answer, you can at http://www.microsoft.com/enable/ DEV / TOOLDEV.HTM found an article about analog input. 4). You can use mouse_event () in NT, the document says this method is outdated, then you can replace it with sendInput (), but find No instructions about this function, I still use mouse_event, there is no problem.

(60) Change the dialog title font?

How to change the font of the dialog title file, change the font in the dialog in the resource, change all the controls of all controls, but I have not changed the title, but I just want to change the title font, do not change the properties of the lesser control. Is it? I missed some obvious options. By looking for some MFC code, I found a CDIALOG module, calling a font method, but the dialog is not public, I believe it will not give me any help.

1). As I know, the title font of the dialog box is the same as other window titles, it can be set through the system-display-attribute-appearance, if you want to do this, I think you should get the WM_NCPAINT handle yourself. To draw a non-user area (including titles), I have never done this, maybe it is a wrong direction. 2). If you are inherited in CVIEW, you can see the following code in the constructor: IF (! MY_CFONT .CREATEPOINTFONT (180, "Helvetica", NULL) Return False; getEditctrl (). SetFont (& my_cfont, true) Next If you want to change a CEDIT control font in the dialog box: You can use the following code:

IF (! my_cfont .createpointfont (180, "helvetica", null) Return False; (Getdlgitem (ID_ANY_CEDIT)) -> setFont (& my_cfont);

(61) How do I know the status of the CWINTHREAD object?

How can I know that a thread is running or has already terminated?

You can use the thread handle to :: getExitCodetRead () function, if the thread has ended, it will return an exit code, if it is still running, return a still_active. However, before it first, set the CWINTHREAD member object M_Bautodelete to false. An additional object is automatically detected at the end of the thread.

(62) How to adjust the size of the control dialog box?

I want users to control its size while the control bar appears. In all examples, when the control is floating, the size can be changed, but when the toolbar is stopped on the frame, it cannot adjust its size, how to implement it?

1) Maybe you missed some attention, I used the CCoolDialogbar class downloaded on the CodeGuru site, and you can also change their size when the toolbar is stopped. 2) I developed an app, its interface and what you said Almost, let me try to explain what I did .1. Inherited a class from the CDialogbar class, named CMYBAR; 2. Increase a member variable in CMYBAR, int m_iwidth; 3. On the CMYBAR onpainT and Painting toolbar (Grab Bar) in OnncPaint; 4. Painting the trajectory when the toolbar is dragged; 5. When release the mouse, calculate the new width of the CMYBAR. You can make M_iWidth equal to the new width by getting the current trajectory position. (Important) getDockingframe () -> recalclayout (); 7. Add a member method in CMYBAR CalcDynamicLayout; 8. In CalcDynamicLayout, when the toolbar is stopped, the M_IWIDTH returns a value. Of course, this is just a very Simple method, you can do better than this. 3) You can try the CREBAR class in VC6.0

(63) How to display CSTATIC class text?

I am writing a small app, I want to display a string of text (cstatic) and whether it is overwritten until the application runtime, these text will always display it.

1) Use createex to create a WS_POPUP window, so that this window is always on the top (Always On TOP) and then implements text display in this window. 2) When establishing a window, use the setWindowPos () function, with & wndtopmost as the first parameter, This will do what you want to do.

(64) What did the message sentence?

I define a handle for WM_LBUTTONDOWN in cparentview, but I built a new CChildView, and the handle is not processed.

1) Take a closer look at Message_MAP in your childview file, there may be a base class in the second parameter to match Begin_Message_Map (Child, Parent). If you use the wizard generator, then you will easily happen this kind of thing .2) Check if the class name and the parent class name in the message image move are correct, such as Begin_Message_Map (CchildView, CParentView). If you use your own message handle manually instead of the wizard, I am sure that your changes are correct. An error parameter or a "const" will change the message image without being called correctly. 3) I guess you must use the class to create your cchildview, and you must be in the selection of the base class. It is selected, and you will modify it in the message image. (65) Why is the tree control flash?

I inherited a class from ctreectrl, displaying nodes in the indent format, now I have encountered some problems, and when the tree is returned twice (once a time for the default, the other for alignment text) Click the node tree Will blink.

1) Try the LockWindowUpdate () API function. 2) Try to join the TVS - Hasbuttons logo,

ModifyStyleex (TVS_HASBUTTONS, 0); .... // DrawingModifyStyleex (0, TVs_haasbuttons); if it no longer flashes, then it is defined as a self-painting property, add CS - OWNDC to PrecreateWindow ().

(66) How can I close the scroll bar in the tree control?

I want to close the scroll bar of the tree control, but it still shows it, how can I hide it?

1) Add TVS_NoscRoll when establishing, pay attention to this point you cannot use the keyboard to implement page, this type requires the COMCT32.DLL4.71 version or above, and to define the #define tvs_noscroll 0x2000 in CommCtrl.h. 2) It is worth trying to try MODIFYSTYLE (WS_VSCROLL, 0), put this code after the establishment, the display.

(67) How to build a window with a scroll bar?

I want to build a sub-window with scrolling, but I don't use the wizard.

If you let your window have a scroll bar, you must first initialize it first. as follows

ScrollInfo Si; Si.cbsize = SizeOf (ScrollInfo); Si.Fmask = SIF_PAGE | SIF_RANGE;

Si.nmin = 0; si.nmax = 100; si.npage = 10; setscrollinfo (sb_horz, & Si);

Si.nmin = 0; si.nmax = 50; Si.NPAGE = 5; setscrollinfo (SB_VERT, & SI); if the program is running, you have to change the scroll when the window is changed or the window is changed, you must reset the scrolling Strip. In the MFC contains class CScrollView, it has built rolls.

(68) How to implement the dialog box?

I have a dialog program that wants it to achieve drag. But whether all news is sent to the CView class, why is it used to use overdrag or ondrop or the like, not a CDIALOG class, why?

You should use the COLLDROPTARGET class, try this:

class CMyOleDropTarget: public COleDropTarget {protected: virtual DROPEFFECT OnDragEnter (CWnd * pWnd, COleDataObject * pDataObject, DWORD dwKeyState, CPoint point) {TRACE ( "DRAG Enter / n"); return DROPEFFECT_MOVE;}; virtual DROPEFFECT OnDragOver (CWnd * pWnd, COLEDATAOBJECT * PDATAOBJECT, DWORD DWKEYSTATE, CPOINT POINT) {Trace ("Drag Over / N"); Return DROPEFFECT_MOVE;};

CMYOLDROPTARGET DROPTARGET;

Bool cdlgdlg :: OnNitDialog () {cdialog :: oninitdialog ();

DROPTARGET.REGISTER (THIS);

Don't forget to call afxoleinit () Bool CDLGApp :: InitInstance () {AFXENABLECONTROLCONTAINER (); afxoleinit ();

}

(69) TRACKMOUSEEVENT ()

I use the trackmouseEvent () function to track if the mouse has left my window, but in the MFC, if I use :: trackmouseevent () system tells me that I didn't define, why?

1). Please use _trackmouseevent2). Incommctrl.h is displayed as _trackmouseevent (), please pay attention to underline .3). May TrackMouseEvent () does not support Win98 (very good in NT), I suggest you combine the WM_MouseMove message and SetCapture () function, you can still control when your mouse moves out of the window.

(70) Strange combination box control

I have a dialog program that there is only a few drop-down feeds. But when the mouse arrow moves to the up and down button of the combo box, it will become "6" or "9", and it will restore it to the original situation. Why is this? ?

1) Maybe your operating system has problems, no restarting one time maybe it (the probability is very small 8% - ()) You can also try the system clearing tool, if this is often, you can really need heavy Put 95 or NT, this is also a good suggestion, you can reload the system every half a year. 2). I guess may be the comctl32.dll file was destroyed. 3). This problem is very likely to be system The resources are not enough, you can try to close some programs, reduce the resolution of the screen to add some system resources.

(71) About using MS SANS Serif font

I have seen many examples of using MS Sans Serif using MS SANS Serif, and the combo box, etc. Such as: m_font.createpointfont (80, _T ("MS Sans Serif")); or m_font.create (-8, ....., _t ("MS Sans Serif"); then I want to ask: 1) The font can be implemented in all versions (including international versions) 2) Is there a better font on the control panel instead of "system" font? If someone did this, how did it set the font size and other related settings? I hope there is a thorough way to select fonts such as combination boxes.

1) I have done it in all the things in all the program interfaces. The message box will display the font selected by the user. The fonts of the menu, the toolbar, and other controls are changed with the user's will. But in the dialog box It is best to use a dialog editor, and its basic font is MS Sans Serif, so I also use this font as all user interfaces. The following is the code I made:

// here's the font I use: SystemParametersInfo (SPI_GETNONCLIENTMETRICS, 0, & ncm, 0); m_fntUI.CreateFontIndirect (& ncm.lfMessageFont); // here's the code to change the font for a wnd and all it's children, andresize the controls appropriatelyvoid ChangeDialogFont (CWND * PWND, CFONT * PFONT, INT NFLAG) {CRECT WINDOWRECT

// grab old and new text metricstextMetric Tmold, Tmnew; CDC * PDC = PWND-> getdc (); cfont * psavedfont = PDC-> SelectObject (PWND-> getFont ()); PDC-> GetTextMetrics (& TMOLD); PDC- > SelectObject (PFont); PDC-> GetTextMetrics (& TMNEW); PDC-> SelectObject (PsavedFont); PWND-> ReleaseDC (PDC);

Long oldheight = tmold.tmheight tmold.tmexternalleading; long newheight = tmnew.tmheight tmnew.tmexternalleading;

IF (NFLAG! = CDF_NONE) {// Calculate New Dialog Window Rectangle CRECT ClientRect, NewClientRect, NewWind NowRect;

pWnd-> GetWindowRect (windowRect); pWnd-> GetClientRect (clientRect); long xDiff = windowRect.Width () - clientRect.Width (); long yDiff = windowRect.Height () - clientRect.Height ();

newClientRect.left = newClientRect.top = 0; newClientRect.right = clientRect.right * tmNew.tmAveCharWidth /tmOld.tmAveCharWidth; newClientRect.bottom = clientRect.bottom * newHeight / oldHeight;

if (nFlag == CDF_TOPLEFT) // resize with origin at top / left of window {newWindowRect.left = windowRect.left; newWindowRect.top = windowRect.top; newWindowRect.right = windowRect.left newClientRect.right xDiff; newWindowRect .bottom = windowRect.top newClientRect.bottom yDiff;} else if (nFlag == CDF_CENTER) // resize with origin at center of window {newWindowRect.left = windowRect.left - (newClientRect.right - clientRect.right) / 2; newWindowRect.top = windowRect.top - (newClientRect.bottom - clientRect.bottom) / 2; newWindowRect.right = newWindowRect.left newClientRect.right xDiff; newWindowRect.bottom = newWindowRect.top newClientRect.bottom yDiff; } PWND-> MoveWindow (newwindowRect);} PWND-> setFont (PFont);

// Iterate Through and move all child windows and change their font.cw * pchildwnd = pWnd-> getWindow (gw_child);

While (PChildWnd) {pchildwnd-> setfont (pfont); pchildwnd-> getWindowRect (WindowRect);

CString strClass; :: GetClassName (pChildWnd-> m_hWnd, strClass.GetBufferSetLength (32), 31); strClass.MakeUpper (); if (strClass == _ T ( "COMBOBOX")) {CRect rect; pChildWnd-> SendMessage (CB_GETDROPPEDCONTROLRECT , 0, (lparam); windowRect.right = Rect.right; windowRect.bottom = Rect.bottom;

pWnd-> ScreenToClient (windowRect); windowRect.left = windowRect.left * tmNew.tmAveCharWidth /tmOld.tmAveCharWidth; windowRect.right = windowRect.right * tmNew.tmAveCharWidth /tmOld.tmAveCharWidth; windowRect.top = windowRect.top * newHeight / Oldheight; windowRect.bottom = windowRect.bottom * newheight / oldheight; pchildwnd-> movewindow (windowRect); pchildwnd = pchildWnd-> getWindow (gw_hwndnext);}}

(72) Why DLL can't find a string in a string table

I created a DLL with the "Use MFC in A Shared DLL" option in the wizard generator, add a string in the string resource, when I use csmystring.loadstring (ids_my_string) csmystring is empty, why?

1) The MFC is called resource by AfxGetResourceHandle. So, if you want to read resources in your DLL should use AFXSetResourceHandle. You can also get it in the return value of LoadLibrary, if you don't want to call the DLL, you can also use the DLLMAIN function. Hinstance parameter. 2) Try using AFX_Manage_State () in your function (in fact each function that is called by the external DLL) 3) I remember the previous list, this problem, try The following two methods: If you use loadLibrary () to call the DLL, it will return a handle that you can use it in AfxSetResourceHandle (). Such as:

hinstnew = Loadbrary (...); ... hinstOld = AfxGetResourceHandle (); AfxSetResourceHandle (hinstnew); LoadString (IDS_MY_STRING); AfxSetResourceHandle (hinstOld); // remember to set this back, // or your night will not be If you don't use LoadLibrary to call the DLL again? You can use the getModule ("You DLL Name" to get the user handle, and if you do it.

(73) Text color about check boxes

Does anyone know how to change the color of the text options in the check box?

1) Have you tried to use ONCTLCOLOR in the control, which will be called before any control, so you can have the opportunity to change the color of the text option. 2) Why do you have to use predrawitem ()? Do you want to do some specific code inside? I think DrawItem () can also be handled. Take the index number and change the color before calling the redraint function.

(74) Serialization and version issues

I need to use a series to read my files. In order to ensure that the file can be implemented in various versions, I made as much as possible, why is it unsuccessful.

A: The following code is that I have used it in the past, I hope I can help you.

// Use this macro to fix the versioning problem in the MFC // Place it at the beginning of your CMyObject :: Serialize implementation - // it will guarantee that the correct version of the class is written to // and read from the archive //// usage: serialize_version (cmyObject) #define serialize_version (this_class) ar.serializeclass (this_class :: getRuntimeClass ());

// For classes which can not use IMPLEMENT_SERIAL (such as abstract // base classes). This guarantees the object can have [Read / Write] [Class / Object] // called on it by placing a schema number in it. It also puts IT IN The // List of Known Class Names (AFX_CLASSINIT) .// Note: this is almost the Same as item_serial_abc // in "MFC INTERNALS", But this version of users AFX_CLASSINIT, / / ​​WITH The Result That IT Works!

#define declare_dynamic_serial (class_name) Declare_serial (class_name)

#define IMPLEMENT_DYNAMIC_SERIAL (class_name, base_class_name, wSchema) _IMPLEMENT_RUNTIMECLASS (class_name, base_class_name, wSchema, NULL) static const AFX_CLASSINIT_init _ ## class_name (RUNTIME_CLASS (class_name)); CArchive & AFXAPI operator >> (CArchive & ar, class_name * & pOb) {pOb = ( Class_name *) ar.readObject (runtime_class_name)); Return Ar;} or can also achieve this:

CMYSERIALROOTDERIVEDCLASS :: serialize (carchive & ar) {// cmyserialroot :: serialize (ar); // <- do not call this here

IF (ar.isstoring ()) {... store derived stuff here} else {int nversion = ar.getObjectschema ();

Switch (NVersion) {Case 1: ... loading derived version 1 stuff here break; case 2: ... loading derived version 2 stuff here break; default: // report unknown version of // this Object break;}} / / serialize the base class version information // -> THEN Serialize the base class ar.serializeclass (runtime_class (cmyserialroot); CMYSERIALROOT :: Serialize (ar);}

(75) Detect and use on_command messages in one control

There is a control (inherited CWnd) in crormview. Can you send its ID in an on_command message, if you use pctrl-> oncommand (id_view_zoom, ..), the compiler reports the parameter does not match, what should I do?

1) Why don't you use pctrl-> post / sendMessage (WM_COMMAND, ID_VIEW_ZOOMIN 2) can be overloaded cyormview :: oncmdmsg. Such as:

BOOL CYourFormView :: OnCmdMsg (UINT nID, int nCode, void * pExtra, AFX_CMDHANDLERINFO * pHandlerInfo) {return pCtrl-> OnCmdMsg (nID, nCode, pExtra, pHandlerInfo) || CFormView :: OnCmdMsg (nID, nCode, pExtra, pHandlerInfo) ;} 3) Use the WM_COMMAND message to see about WM_COMMAND and CWND: PostMessage () help.

DWORD WPARAM; HiWord (WPARAM) = WNOTIFYCODE; // Notification CodeLoword (WPARAM) = id_view_zoom; pctrl-> postmessage (wm_command, (wparam) WPARAM, PCTRL-> M_HWND); 4) can do this, but not like you practice, You must get the handle or CWND pointer and use it in the handle :: postMessage () or: postmessage (); using CWnd :: SendMessage () or cWnd :: postmessage () Try this.

CMYCTRL * PCTRL;

/ * Call getdlgitem () from an instance of your form view * / pctrl = (cmyctrl *) getdlgitem (IDC_MYControl);

IF (PCTRL! = NULL && :: Iswindow (pctrl-> getsafehwnd ()) PCTRL-> SendMessage (WM_COMMAND, / * WPARAM * /, / * LPARM * /); // See WM_Command Description on Help / MSDN for a Detailed Explanation of // {w | l} param

(76) Why is the primary application cannot close when there is a sub-window in the MDI program.

I added in an MDI program CRichEditView document template, in the sub-window view I added some code below .StartReport (void) {CReportFrame * rpt; CReportDoc * rptDoc; // First get the right document templatePOSITION pPos = theApp.GetFirstDocTemplatePosition (); Theapp.getnextdDector (PPOS); THEAPP.GETNEXTDOCTEMPLATE (PPOCTemplate * Ptemplate = theapp.getnextdDoCtemplate (PPOS);

// verify validityassert (PTEMPLATE! = NULL); assert_kindof (cdoctemplate, ptembly);

// create the frameptdoc = new creportdoc; rpt = (create-> createnewframe (rptdoc, null); PTEMPLATE-> InitialUpdateFrame (RPT, RPTDOC);

// Get access to the display areaCReportView * rptView = static_cast (rpt-> GetActiveView ()); CRichEditCtrl & rptCtrl = rptView-> GetRichEditCtrl ();} CReportFrame inherited CMDIChildWndCReportDoc inherited CRichEditDocCReportView inherited from CRichEditView not close the front if I close the program New aspects, debugger will consider that the program is still running (still exists in the program manager) I need to close the program with Stop Debugging in the debug menu; if I handle the view, the program will be closed. If there is anything different If the program will ask if the program is hand-off, you will ask if you save. So how can I close the program?

1) I also hit the dialog box, the window can't automatically shut down, this is mainly due to the incorrect object of the inheritance. AFXGETMAINWND () should usually be set in the main program. Your program makes me confused, and use multiple getNextDoctemplate (PPOS), which usually causes some loops when these document pointers are null. Are you in your document template? I have been carefully calculated? This may generate some BUGS I suggest to find the current document template with cdoctemplate :: CreateNewDocument () instead of your "New CreportDoc" 2) Remember a public rule, close the program to close all View.

(77) Rolling LPTODP failed

In Windows98 / 95, when you give the cursor pointer position greater than 32767 or less than -21768 function CDC :: lptod will fail, the program works on NT but in 95/98, there is a problem. LPTODP is The following functions are called: setscrollsizes (mm_himetric, sizetotal); function is called in the CScrollView. I am using the Himetric mapping method, and this problem will appear when I want to expand A4 by 150%. How can I solve this problem?

1) There is a problem in 95, and the GDI in 95 is not 32. When we develop a program with a program, it is manually instead of being an editing vector image to complete the conversion. (Also in NT Problem) 2) In short, the 32-bit parameters of CScrollView or CWnd will fail because 95/98 is not a real 32-bit operating system, which still contains 16-bit code. For example, ScrollBars still only accepts 16-bit values. Adjustment range. NT is a real 32-bit operating system, there is no confusion. When you have to face similar scrolling big documents in 95, we can only write some code to implement the actual position of scrolling, when it When you exceed -32K or 32K, you must also make some mappings in your application. As a related point (maybe you have already hit this problem) If you have scrolling messages in the MFC, such as: void csomewnd :: The NPOS parameters in ONVSCROLL (Uint NSBCODE, UINT NPOS, CSCROLLBAR * PSCROLLBAR) are only 16 long. Overcome this limit can be run using the Scroolinfo structure :: getScrollInfo.scrollinfo structure NTRACKPOS is a true 32-bit. (78) ODBC license issues

I have a program to use an MS Access database through ODBC, but I have hit an error, and the system displays "Records Can't Be Read; No Read Permission On Table Session". (Record cannot be read, form is not allowed)

First I assume that the Access database has a default user "admin", which can complete "ODBC; UID = Admin". Then, when you inherit the CRecordset class, you don't have to take parameters, but the following method may be better :

Open (CRecordset :: Dynaset, NULL, CRECORDSET :: UsebookMarks | CRecords) Of course, you must provide DSN to represent the database of connection names under ODBC.

(79) Weird font

We have an MFC application, the main window is drawn on the customer area. We hope to display text in the customer area, erase when not needed, so we get a DC (cclientdc), then set the font And the text color start writing text. When we erase, we use the same font, the same place with background colors of text. This method is working very well, but occasionally text does not completely rub In addition, some pixels are still visible. It seems that it is usually slightly slightly fat when writing text, just like bold. The font is used when writing text, and there is no adjustment in the future. Below is our use Writing and erase function .void csign :: DrawsignName (CDC * PDC) {Int Oldbkmode;

// select the appriate fontcfont * PoldFont = (cfont *) PDC-> selectObject (psignnamefont);

Oldbkmode = PDC-> setBkmode (Transparent);

// determine the color of the textif (IssignNameVisible ()) PDC-> setTextColor (Acolus [Sign_Name_COLOUR]); ELSE PDC-> SetTextColor (Acolus [Device_Invisible_COLOUR]);

// Draw the textpdc-> textout (m_pointnamecoords.x, m_pointnamecoords.y, m_strname);

// restore the previously used font and background modepdc-> selectobject (PoldFont); PDC-> setBkmode (OldBkmode);

} // DrawSignName function is called in the message handle, and the DC in the parameter is built: cclientDC DC (AFXGETMAINWND ()). The font is created when the program is initialized: psignnamefont = new cfont; psignnamefont-> createfont (PsignNameFont-> CreateFont) 10, 5, 0, 0, 150, False, False, 0, ANSI_Charset, Out_Default_Precis, Clip_Default_Precis, Default_quality, DEFAULT_PITCH | FF_SWISS, "Helvetica"); Is there a problem with two DCs pointing to the same customer window? DrawsignName () in the program is called by multiple message handles. 1) Add the following code:

{m_strname.empty (); invalidate (); updateWindow (); more stuff ;;} The above code generates a WM_ERASEBKGND message, which will fill the window with background colors, then call overdraw (), then just put characters Card is set. 2) I don't know why the program can't work normally, but I have an idea (it will be faster) can use a background color rectangular painting with a background color. I don't know why you want to use transparent text, which will give a lot of work to the graphics system. The reason why the font has this situation, whether you have the graphic fidelity software that text output? It will bring you confused. 3) You just want to simply use a pointer to save a GDI object pointing to the DC, and try to call it again to point to the correct object. IMHO, this is not the right way (I don't know if this is the only reason for displaying abnormal) to convert it into a Windows handle is correct: //// Creating: // psignnamefont = new cfont; psignnamefont- > CreateFont (10,5,0,0,150, FALSE, FALSE, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, "Helvetica"); // Now converting into a windows handlem_hSNFont = (HFONT) pSignNameFont-> GetSafeHandle (); Save an object is not safe.

(80) Self-painted list box

A long time ago, someone disabled the self-painted list box control code, and the appearance of the self-painted list box is like a standard list box. At that time, I had an idea to collect the code of all the self-draw controls developed by the programmer, so the programmer They can use existing code. I would like to ask about the code on the MFC site on the MFC site on the list of lists or other controls?

1) Self-painting list box code is as follows, see if it is what you want.

HEADER FILE

class CCustomListBox: public CListBox {public: // Operations DECLARE_DYNCREATE (CCustomListBox) int AddLBItem (LPSTR); void HandleSelectionState (LPDRAWITEMSTRUCT lpdis); void HandleFocusState (LPDRAWITEMSTRUCT lpdis); virtual void DrawItem (LPDRAWITEMSTRUCT lpDIS);}; cpp file

Implement_dyncreate (CCUSTOMLISTBOX, CLISTBOX)

INT CCUSTOMLISTBOX :: AddLbitem (LPSTR Itemstr) {addstring ((lpcstr) itemstr); Return 0;}

Void CCustom (LPDRAWITEMSTRUCT LPDIS) {CDC * PDC = CDC :: fromHandle (LPDIS-> HDC);

IF ((LPDIS-> ItemState & ODS_SELECTED & (LPDIS-> ITEMATION & (ODA_SELECT | ODA_DRAWENTIRE))) {PDC-> InvertRect (& lpdis-> rcitem); PDC-> DrawFocusRect (& lpdis-> rcitem);}

IF (! (lpdis-> itemState & ods_selected) && (lpdis-> itemaction & oda_select) {PDC-> InvertRect (& lpdis-> rcitem); PDC-> DrawFocusRect (& lpdis-> rcitem);}}

void CCustomListBox :: HandleSelectionState (LPDRAWITEMSTRUCT lpdis) {// Ordinarily could check for "if (lpdis-> itemState & ODS_SELECTED)" // and do drawing for selected state, "else" draw non-selected state.// But second call TO InvertRect Restores Rectangle to Original // State, So Will Just Call Function WHETER SETER SELECTED ORESELECTED.

:: InvertRect (LPDIS-> HDC, (LPRECT) & lpdis-> rcitem);

void CCustomListBox :: HandleFocusState (LPDRAWITEMSTRUCT lpdis) {// Ordinarily would check for "if (lpdis-> itemState & ODS_FOCUS)" // and do drawing for focus state, "else" draw non-focus state.// But second call to DrawFocusRect restores rectangle to original // state, so will just call function whether focus or non-focus.// New to Windows 3.0, this function draws a black dashed-rect // border on the border of the specified rectangle :: DrawFocusRect (lpdis-> HDC, (LPRECT) & lpdis-> rcitem);} 2) http: toronto.planeteer.com/~zalmoxe/

(81) CWnd :: getMenu () problem

I have a program with the following code:

CWND * PWND = CWnd :: GeForegroundWindow (); if (pwnd == null) Return False; cmenu * PMENU = PWND-> getMenu (); if (pMenu == null) Return False; for (int i = 0; i getMenuItemcount; i ) {pmenu-> getMenuItemId (...); pmenu-> getmenustring (...);} In addition to outside the IE window, other windows work is normal, how can I? Usually used in the IE window, if not use this method, what is the way to use?

IE has a definition menu that is the pop-up menu in a custom family control. So you can no longer use this method, try to handle WM_InitMenupopup or WM_INITMENU. There are similar examples in the CD of the VC (About Cut and Copy) You can list all menu items when you get a message handle. The above code does not work may be because Microsoft's self-drawn menu items use different formats, you want to understand if the menu and the marker are self-drawn, you can use this method to test lpmii-> ftype & mft_ownerdraw .IPMII is a menu structure that returns the resulting menu item. LPMII-> DWTYPEDATA Returns the type of (menu) project, if the value returned by DWTYPEDATA is nothing to use, LPMII-> DwItemData will point to the string structure in the menu item at the beginning of a (program). The above methods are better because there are now many programs use the custom menu.

(82) Production pop-up window with MFC

I am trying to use MFC to make pop-up windows, I have seen some articles about establishing pop-up windows, they are using CWND objects. But how do you implement in the documentation and window structure?

You can create a non-modular dialog (using the CREATE function), you can create a window, a sub-window, and more. If you must be implemented in a document, the window structure, you can also use the CCReateContest class. The following is an example of establishing an MDI window: {lpctstr lpszclassName = null; ccreatecontext ccontext;

Ccontext.m_pnewviewclass = runtime_class (cmyview)

DWORD DWSTYLE = WS_CHILD | WS_VISIBLE | WS_OVERLAPPEDWINDOW & ~ WS_THICKFRAME & ~ WS_MAXIMIZEBOX;

// Tod Add your Specialized code Here and / or call the base class

if (CMDIChildWnd :: Create (lpszClassName, lpszWindowName, dwStyle, pParentWnd-> rectDefault, pParentWnd, & cContext)) {InitialUpdateFrame (NULL, TRUE); CScrollView * pView = (CScrollView *) GetActiveView ();

IF (PView) PView-> ResizeParentTofit (FALSE);

Return true;} else returnText has a member M_PCurrentDoc, you can use it to assign a document to the appropriate window.

(83) How to cancel a pop-up menu

I have an application that does not display the window (using a sw_hide parameter when the window is created, it only shows an icon at the task bar, I do this: Notifyicondata TNID;

tnid.cbSize = sizeof (NOTIFYICONDATA); tnid.hWnd = m_hWnd; tnid.uID = 1; tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; tnid.uCallbackMessage = MYWM_NOTIFYICON; tnid.hIcon = AfxGetApp () -> LoadIcon (IDI_ICON1) LSTRCPYN (TNid.sztip, "Giroimag Image Mail Exchange", Strlen ("GiroImag Image Mail Exchange") 1);

Shell_notifyicon (Nim_ADD, & TNID); When I click on the task bar, the program displays a pop-up menu: CMenu M_Menu;

m_menu.createpopupmenu ();

m_Menu.AppendMenu (MF_STRING, IDM_ABOUT, "Op & 1"); m_Menu.AppendMenu (MF_SEPARATOR, 0); m_Menu.AppendMenu (MF_STRING, IDM_CONFIG, "Op & 2"); m_Menu.AppendMenu (MF_STRING, IDM_STATUS, "" Op & 3 "); m_Menu .AppendMenu (MF_SEPARATOR, 0); m_Menu.AppendMenu (MF_STRING, IDM_SEND, "Op & 4"); m_Menu.AppendMenu (MF_STRING, IDM_RECEIVE, "Op & 5"); m_Menu.AppendMenu (MF_SEPARATOR, 0); m_Menu.AppendMenu (MF_STRING, IDM_CLOSE , "OP & 6"); Point P; GetCursorpos (& P);

m_menu.trackpopunu (TPM_LEFTALIGN | TPM_RightButton, P.X, P.Y, this); to this, the program is running is normal, the problem is if I don't choose any menu to cancel it? I think that I can click ESC or click outside the menu to cancel, but the fact is not the case. I also tried to use the TrackPopUpMenuex function in Win32API but not used, what should I do?

1) The easiest way to add the "Cancel Menu" command in the message image. 2) Although your main window is not visible, you can call M_Menu.trackPopUpMenu (); time it will be the forefront. 3) Before you pop up the menu, set your window to the forefront window, call the following code, the problem will solve it.

Point P; getCursorpos (& P);

// increase the thread priority by invoking setgroundwindow.setForegroundWindow ();

M_Menu.trackPopupMenu (TPM_LEFTALIGN | TPM_RightButton, P.x, P.Y, this); 4) Before you call TRACKPOPUPMENU (), you must call setForegroundWindow, then call PostMessage (M_HWND, WM_NULL, 0, 0):

POINT point; GetCursorPos (& point); SetForegroundWindow (m_hWnd); TrackPopupMenu (hPopup, TPM_RIGHTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, point.x, point.y, 0, m_hWnd, 0); PostMessage (m_hWnd, WM_NULL, 0, 0);

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

New Post(0)