VCMFC Q & A 200409

xiaoxiao2021-03-06  54

Laiyiling collects the finishing, and later, if there is time, it will make some information, which is easy to read.

Q] How to determine whether there is text data in the clipboard? Answer] COLEDATAOBJECT DATAOBJECT; DataObject.attachClipboard (); if (DataObject.isdataavailable (cf_text)) {..... // has text data} Q] How to get ComboBox's Edit handle? Answer] CEDIT * PEDIT = (CEDIT *) CCOMBOBOX.GETWINDOW (GW_CHILD) Q] Get the current user directory, namely: C: / Documents and settings / ... Answer] ShgetspecialFolderPath (Null, (LPTSTR) Szpath, CSIDL_PERSONAL, FALSE ; Ask: How to change the height of the status bar? Answer] M_WndStatusBar.getStatusbarCtrl (). SetminHeight (40); Q] Dynamic adjustment control The problem answer】 When executing WM_SIZE, the possible control has not been created by the program, you must make sure your control is created Can you use MoveWindow, 1, you can set a BOOL variable, the initial value is false, the last value of OnInitDialog becomes true, and this variable is determined in WM_SIZE, and only the MoveWindow operation is performed when it is true. 2, you can also use :: iswindow (control .getsafehWnd ()) to determine if the control is created, only the MoveWindow operation is performed when it is true.

Q] How to get a combination key in PretranslateMessage (), such as Ctrl F1 answer] if (PMSG-> Message == WM_KEYDOWN && PMSG-> WPARAM == VK_F1 && getKeyState (vk_control) & 0x80) Q] What is the difference between SendMessage and PostMessage? Answer] Postmessage will not wait after sending a message. If you send it back, you will be able to see the message after sending a message after sending a message after sending a message. You can see: http: // msdn. Microsoft.com/msdnmag/issues/1200/C/ Q] How does the document view do not open any document after the program starts running? Answer] MDI joins before the ProcessShellcommand function in the program's InitInstance: cMDinfo.m_nshellcommand = ccommandlineinfo :: Filenothing SDiinitInstance function About the onfilenew call Remove question] How to send a click message to a button? A] SendMessage (WM_COMMAND, ((WPARAM) BN_CLICKED) << 8 | (WPARAM) IDC_BUTTON, 0L); :: PostMessage (m_hWnd, WM_COMMAND, MAKEWPARAM (IDOK, BN_CLICKED), 0); :: SendMessage (m_hWnd, WM_COMMAND, MakewParam (IDOK, BN_CLICKED), 0); ask] SDI project, always prompt me to save when closing the window? How can I not let this window pop-up directly close? Answer] void cmainframe :: onClose () {// Todo: add your message handler code here and / or call default getActiveDocument () -> setmodifiedflag (false); // joined this sentence! CframeWnd :: OnClose ();} Q] How to get the text content of other applications? Answer] Send a WM_GETTEXT message, not directly using the getWindowText function, if you use SDK, change CWND to hwndcwnd * pwnd = getotherappWindow (); tchar BUF [512]; PWND-> SendMessage (WM_Gettext, Sizeof (buf) / sizeof (Tchar) (lParam) (void *) BUF); seeing this here is certainly asking? Why is the getWindowText function? Is the getWindowText function not sent a WM_GETTEXT message? Not. The getWindowText function only sends a WM_GETTEXT message when the window belongs to the current process. If the window belongs to a different process, the behavior of the getWindowText function is different. The MSDN's documentation is very clear: If the target window belongs to other processes, and the window has a title bar. The getWindowText function returns the title of the window. Returns NULL if the window does not have a title bar. Microsoft is the beginning of such a getWindowText function. That is to say, we can only get the title of other process windows with the getWindowText function, and you cannot get the text content of the other process window, such as editing the mine, the combo box.

Q] How do you know which files have been opened in a process? Answer] http://www.codeguru.com/cpp/wp/system/procesSModules/Article.php/c2827 Q] How to use CMylistCtrl (ie custom control) to replace CLISTVIEW Control? A] I made a custom control derived from CWnd, and now I want to use it as a view. My first solution was to embed the control into the view and handle OnSize in the view to position the control over the client area. The problem is that mouse messages go to the control and can not be overridden in the view. The keystroke messages go to the view and must be manually forwarded to the control.I read about CCtrlView as a base class for common controls. I've even managed to Write the View Around IT (I Believe That You Wrote About this in An Issue of MSJ), But I Could Not get it to work with my cwnd-based control. can this be done, and how? For more information, see http: / /msdn.microsoft.com/msdnmag/issues/01/11/C/default.aspx Asked? Who can tell how to implement API hook? A] My motivation for writing this article was the need for a really simple hooking framework, that will offer an easy to use interface and ability to capture different APIs. It intends to reveal some of the tricks that can help you to write your own spying system. It suggests a single solution how to build a set for hooking Win32 API functions on NT / 2K as well as 98 / Me (shortly named in the article 9x) family Windows. for the sake of simplicity I decided not to add a support for UNICODE. However, with some minor modifications of the code you could easily accomplish this task.For more infomation please read the following article, for more information see http://www.codeguru.com/Cpp/WP/system/misc/ Article.php / c5667 / Q] // Activate the current screen saver can send the following message answer] PostMessage (wm_syscommand, sc_screensave, 0); ask] How to get the screen DC? Answer] CDC * DC = CDC :: fromHandle (:: getdc (null)); ask] How to display Chinese characters in the status bar?

Answer] M_WndStatusBar.SetPanetext (NPANE, SMSG); NPANE is the serial number of the lattice, starting SMSG from 0 SMSG is displayed] TabCtrl Response Double click Close answer] You can use the setWindowlong settings to ask] CHAR SZPATH [1000]; SHGETSPECIALFOLDERPATH (this-> getsafehwnd (), szpath, csidl_desktop, false; ask: How to program the display attribute of the system file? Answer] Directly modify the registry can. HKCU / Software / Microsoft / Windows / CurrentVersion / Explorer / Advanced Value Hidden, when this value is 2, "Does not display hidden files and folders" When this value is 1, it is "display all files and folders" Q] How to determine if one is being used? Answer] Handle HF = Createfile (cname, generic_read, 0, null); if (hf == invalid_handle_value) {MessageBox ("This file is being used, please turn off some programs Try"); Return; } CloseHandle (HF); How do you enter a parameter when debugging command line parameter programs? Answer] Project | Seeting | Debug Program Arguments Enter your parameters] About the properties of the combo box】 If the combo box has an ink to pull the Select Properties (Droplist), the member variable directly associated can only be an int type. You need a getlbtext () function to get the currently selected text. (This is one of the most cases when we use the combination box) If the combination box can enter the string (DropDown), you can only associate a member variable of the CString type. To get the currently selected serial number requires its own constructor to complete the visual length of the ComboBox drop-down box, the specified RECT height is the height of the Combox drop-down box.

Q] How do I program to turn on the display? Answer] SendMessage (hwnd, wm_syscommand, sc_monitorpower, -1); // Open Display SendMessage (HWND, WM_SYSCOMMAND, SC_MONITORPOWER, 1); // Turn off the monitor] How to control the display and hide of the system taskbar? Answer] // Hide Windows System Tasklet :: ShowWindow ("Shell_TrayWnd", NULL), SW_HIDE); // Restore Windows System Task Bar Normal Display: ShowWindow ("Shell_TrayWnd", NULL) , Sw_show); ask] How to remove the horizontal scroll bar? Answer] long style = getWindowlong (Handle, GWL_Style); style | = tvs_nohscroll; setwindowlong (handle, gwl_style, style); :: showwindow (hwnd, sw_hide); ask: How to remove the scroll bar at CFormView? Answer] In the OnInitialUpdate function, use the following statement to OK, setscrollsizes (mm_text, csize (0)) Q] How to use cruntimeclass's m_pnextClass, I added a class that inherited from COBJECT, which realized serialization, but get it The m_pnextclass of the changed cruntimeclass is empty. Why? Is there a string name given to a class, such as "cmyobj", via cruntimeclass * pclass = ruventime_class (cmyobj); pclass-> createObject (); create an object. Note "CMYOBJ "Unlike CMYOBJ, whether it can be automatically converted, or use the cruntimeclass field m_lpszclassname to match (how to get the header of the list) answer] 1) m_pnextClass is empty, indicating that your class may be on the tail of the list! 2) may be implemented, part of the code as follows:! CObject * GetShapeClass (CString strClassName) {CRuntimeClass * pClass; AFX_MODULE_STATE * pModuleState = AfxGetModuleState (); for (pClass = pModuleState-> m_classList; pClass = NULL; pClass = pClass-> m_pNextClass) {IF (pclass-> m_lpszclassname == 0) {return (pclass-> createObject ());}} Return Null;} The pointer returned is the COBJECT type, you can convert to the correct type! Q] How to program the icon of a folder? Answer] Just establish the Desktop.ini file under the specified folder, its contents are as follows [.shellclassInfo] iconfile = E: / Resources / Phon/Con/tree5s.icioInetONDEX=0 Change the value of the iconfile for your icon and set this Folder As the system properties] How does the VC program prevent multiple boots? Answer] Initialization functions create mutual exclusion, judgment return value BOOL cyourapp :: InitInstance () {handle handle; handle = createmutex (null, false, _t ("makeesheet3.0"

)); If (handle == null) Return False; if (getLastError () == error_Already_exists) {AFXMessageBox ("Makesheet3.0 is running!", MB_ICONSTOP); Return False;} ......} Or use atoms:

#define atomname "MyProgramNameAtom" // This string can take yourself, try to get special

INT WINAPI WINMAIN (Hinstance Hinstance, Hinstance HPREVINSTANCE, LPSTR LPCMDLINS, INT NCMDSHOW) {atom atom; // Program Atherence, it is determined whether the atom exists if the IF (GLOBALFINDATOM (Atomname)) Return 1; // The program has been running directly, here, directly exit Atom = GlobalAddatom (atomname); // ..., before your code // delete atoms GlobaldeleTeatom (Atom); Return 1;} Reference: http://msdn.microsoft.com/msdnmag/issues/ 0900 / c / default.aspx question] Who can introduce the usage of the assert function? Answer】 Assert () is a macro that is often used when a debugger is running. It calculates the expression in parentheses when running. If the expression is false (0), the program will report an error and terminate the execution. If the expression is not 0, continue the following statement. This macro usually has a significant illegal data in the judgment program, and if the termination program is stopped, it is easy to find errors. Assert is only valid in the Debug version, if compiled as a release version is ignored. Assert macro definitions #define assert (f) / do / {/ if (! (F) && AFXASSERTFAILEDLINE (this_file, __line__)) / afxdebugbreak (); /} While (0) / assert (logical expression) The logical expression value is fake, pops up the debug command window, prompting which file of which file is asserted in anyone! Q] How to assign a designated disk space when establishing a file? Answer] int ILENGTH = 100000; cfile file; file.open (filename, cfile :: modecreate | cfile :: modewrite); file.setlength; this is controlled by file operation, or refer to Chapter 17 describes the file mapping. Q] How to make the dialog box with segmentation? Answer] Reference: http://www.codeproject.com/splitter/zsplitter.asphttp://www.codeproject.com/splitter/simpledlgsplitter.asp Q] Whoever has been under unicode, export .csv file, how to write Chinese character? Answer] It should be written in text! Of course, you can't use the CSTDIOFILE class, because he doesn't support Unicode's read and write, I have given you a reference #ifndef __textfile_h # define __textfile_h

Class CTextFile: Public cfile {public: Virtual Bool ReadString (cstring & rstring) {#ifdef _unicode f (getPosition () == 0) {Seek (2, cfile :: begin);} #ENDIF TCHAR TC; BOOL BFLAG = FALSE; Rstring.empty (); while (cfile :: read (& tc)) {switch (tc) {case 0x0d: Break; case 0x0a: bflag = true; break; default: rstring = tc;}

IF (bflag) Break;} return (! bflag && rstring.isempty ())? False: true;

Virtual Void WritestRing (LPCTSTR LPSZ) {#ifdef _unicode if (getPosition () == 0) {char TC [2]; TC [0] = (char) 0xFF; TC [1] = (char) 0xfe; cfile :: Write (TC, 2);} #ENDIF CFILE :: Write (LPSZ, _TCSLEN (LPSZ) * Sizeof (tchar));}}; # endif //! __ textfile_h Q] How to get the MAC address of the specified network card serial number? A reference for] a function void CGetMacAddrDlg :: GetOneMac (int AdapterIndex) {NCB ncb; UCHAR uRetCode; ASTAT Adapter; memset (& ncb, 0, sizeof (ncb)); ncb.ncb_command = NCBRESET; ncb.ncb_lana_num = AdapterIndex; // Specify the NIC number // First send an ncbreset command to the selected network card for initialization uretcode = netbios (& ncb);

MEMSET (& NCB, 0, SIZEOF (NCB)); ncb.ncb_command = ncbastat; ncb.ncb_lana_num = adapterIndex; // Specify NIC number

STRCPY ((char *) ncb.ncb_callname, "*"); // Specify the variable of the returned information storage NCB.ncb_buffer = (unsigned char *) & adapter; ncb.ncb_length = sizeof (adapter);

/ / Send the ncbastat command to get information URETCODE = NetBIOS (& NCB); if (uretcode == 0) {// format the NIC MAC address into commonly used 16-in-form, such as 0010-A4E4-5802 CSTRING STRMACADDR; STRMACADDR . Format ("% 02x% 02x-% 02x% 02x-% 02x% 02x / n", adapter.adapt.adapter_address [0], adapter.adapt.adapter_address [1], adapter.adapt.adapter_address [2], adapter .adapt.adapter_address [3], Adapter.adapt.adapter_address [4], Adapter.adapt.adapter_address [5]); // number and the card address stored in the array ADPTSTRCT AdptSt; AdptSt.nIndex = AdapterIndex; AdptSt.strMac = strmacaddr; m_arradapters.add (adptst);}}

Void cgetmacaddrdlg :: ONGETDR () {NCB NCB; uchar uretcode; lana_enum lenum; int i = 0; Memset (& NCB, 0, SIZEOF (NCB)); ncb.ncb_command = ncbenum; ncb.ncb_buffer = (uchar *) & lenum; Ncb.ncb_length = sizeof (lenum);

/ / Send the ncbenum command to the network card to get the network card information of the current machine, if there is a network card, each network card number, etc. URETCODE = NetBIOS (& NCB); // Get all NIC information for (i = 0; i

BHO (Browser Help Objects) is a COM component that implements a specific interface. After the development of a good BHO plug-in is registered in a specific location, every time the Microsoft's browser starts, the BHO instance will be created. In the project works in the browser, BHO will receive a lot of events, such as browsers browse new addresses, forward or retreat, generate new windows, browser exit, etc.; BHO can implement and browser in response to these events Interaction.

Below, we first introduce the working principle of BHO. Above we have mentioned that Bho is a COM component, and it must implement the IObjectWithSite interface. These components must be registered as sub-keys under HKEY_LOCAL_MACHINE / SOFTWARE / Microsoft / Windows / CurrentVersion / Explorer / Browser Helper Objects in addition to registering COM Server Microsoft has reserved space for these components when designing browsers. Whenever the browser starts, the browser will first view whether there is a registered BHO CLSID in the above registry; if there is any example, an instance is created, and the BHO instance is initialized to establish an interactive connection. (Note: The BHO instance is only released when you create its browser window destruction.) The following figure demonstrates the creation of BHO: successfully created BHO, not only get a variety of standard browser operations, and respond You can also customize interface elements of the browser's menu, toolbar; or install the hook function to monitor the browser. It is worth noting that using the BHO plugin, the Internet browser requires 4.0 or more version; if it is a file browser, the operating system requires Windows 95/98/2000 or Window NT 4.0 or higher, and the shell is over 4.71 or more. Here is a list of systems that support BHO features:

Shell version operating system version support BHO 4.00 Windows 95 and Windows NT 4.0 (IE version 4.0) only IE4.0 4.71 Windows 95 and Windows NT 4.0 (IE version 4.0) IE and file browser 4.72 Windows 98 IE and file browser 5.00 Windows 2000 IE and File Browser

Next, the author will introduce how to develop BHO plug-ins, the development environment is VC6.0 (using ATL), install Internet Development SDK in Platform SDK. First, start the VC's ATL COM AppWizard, generate a project name BHOPLUGIN, and the rest use the default settings. Then, let's step down in detail. The first step is to add an ATL Object to the project. VC menu insert-> New ATL Object ..., select "Internet Explorer Object" in the pop-up dialog box, enter the COM class name (enter Eyeonie after Short Name, other items will be generated). After completing, we can see the CEYEONIE class has a base class IObjectWithSiteImpl, which is a template class that implements the IObjectWithsite interface. In the second step, implement the interface method of IObjectWithsite. Prior to this, we must first define several member variables: ccomqiptr MwebBBBBROWSER2, (need to join #include "encisp.h") to save your browser component pointer; DWORD MCOOKIE for saving and browse Connection ID of the device. IObjectWithsite has two interface methods: setsite and getsite. We only need to overload Setsite. Increase in the function declaration EyeOnIE.h STDMETHOD (SetSite) (IUnknown * pUnkSite), in EyeOnIE.cpp achieve the following: STDMETHODIMP CEyeOnIE :: SetSite (IUnknown * pUnkSite) {USES_CONVERSION; if (pUnkSite) {mWebBrowser2 = pUnkSite; if (mWebBrowser2 ) {RETURN RegistereventHandler (TRUE);}}}

HRESULT CEyeOnIE :: RegisterEventHandler (BOOL inAdvise) {CComPtr spCP; // Receives the connection point for WebBrowser eventsCComQIPtr spCPC (mWebBrowser2); HRESULT hr = spCPC-> FindConnectionPoint (DIID_DWebBrowserEvents2, & spCP); if ( Failed (HR)) Return HR;

IF (inadvise) {// pass the evenetlers to the contact (}), & mcOokie);} Return HR;} Return HR;} Return HR;} As seen, the parameters of Setsite actually point to the browser component. In the SetSite implementation, we first save the browser component pointer, and then register the BHO to the browser as an event processor. In the third step, implement the IDispatch interface method. Event processing is also implemented in Idispatch :: Invoke (the ID of each event is defined in EXDISPID.H). BHO may receive a lot of events, but we only need to respond to the part of our interested. First, add a statement of this function in Eyeonie.h. In the implementation of Eyeonie.cpp, the author tries to respond to the event DISPID_BEFORENAVIGATE2 issued prior to the browser to browse an address, to achieve a simple URL filtering, the code reference is as follows: stdmethodimp CEyeOnIE :: Invoke (DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS * pDispParams, VARIANT * pvarResult, EXCEPINFO * pexcepinfo, UINT * puArgErr) {USES_CONVERSION; if (! pDispParams) return E_INVALIDARG;

Switch (dispidmember) {/// The parameters for this dispid area as stock: // [0]: Cancel flag - vt_byref | vt_bool // [1]: http headers - vt_byref | vt_variant // [2]: address of HTTP POST DATA - VT_BYREF | VT_VARIANT / / [3]: target frame name - vt_byref | vt_variant //////byref | vt_variant // [5]: url to navigate to - vt_byref | vt_variant /// [6 ]: An object that evaluates to the top-level or frame // WebBrowser object corresponding to the event // case DISPID_BEFORENAVIGATE2: {LPOLESTR lpURL = NULL; mWebBrowser2-> get_LocationURL (& lpURL); char * strurl; if (pDispParams->. Cargs> = 5 && pdispparams-> rgvarg [5] .vt == (vt_byref | vt_variant)) {ccomvariant varURL (* pdispparams-> rgvarg [5] .pvarval); varURl.change type (vt_bstr); strurl = ole2a (varURL .BSTRVAL);} IF (strurl, "girl.com")) {* pdispparams-> rgvarg [0] .pboolval = true ;:: messagebox (null, _t ("The page has been banned!"), _T ("Warning"), MB_ICONSTOP); returnid;} case DISPID_NAVIGATE2: BREAK; CASE DISPID_DOCUMPLETE: BREAK; CASE DISPID_DOWNLOADBEG In: Break; Case Dispid_downloadComplete: Break; Case Dispid_newwindow2: Break; Case Dispid_quit: RegistereventHandler (false); Break; default: Break;

Return S_OK;} We see that when the new address of the user browses "girl.com" characters, the browser pops up a warning dialog and stops further action. It is also worth noting that in the response of the Dispid_quit event (the browser will exit), we log out of the BHO event processor. The fourth step, because BHO may be loaded by the file browser. If we don't want this, we have to judge the loader in Dllmain, refer to the following: Extern "C" Bool WinApi Dllmain (Hinstance Hinstance, DWORD DWREASON, LPVOID / * LPRESERVED * /) {if (dwreason == DLL_PROCESS_ATTACH) { . // Check who's loading us // If it's Explorer then "no thanks" and exit ... TCHAR pszLoader [MAX_PATH]; GetModuleFileName (NULL, pszLoader, MAX_PATH); _ tcslwr (pszLoader); if (_tcsstr (pszLoader, _T ( "explorer.exe"))) return FALSE; _Module.Init (ObjectMap, hInstance, & LIBID_BHOPLUGINLib); DisableThreadLibraryCalls (hInstance);} else if (dwReason == DLL_PROCESS_DETACH) _Module.Term (); return TRUE; // ok} last Don't forget to modify the registry file, add BHO's registration information. EyeOnIE.rgs add the following code in the following documents: HKLM {SOFTWARE {Microsoft {Windows {CurrentVersion {Explorer { 'Browser Helper Objects' {{6E28339B-7A2A-47B6-AEB2-46BA53782379}}}}}}}} Note that { 6E28339B-7A2A-47B6-AEB2-46BA53782379} is the author of this Bho's CLSID, if you develop Bho yourself, you should fill in your CLSID correctly.

Ok, a simple BHO development has been completed. (You can download the instance source code for your own home page http://hqtech.nease.net.) There are many features that the BHO plug-in can be implemented, such as web content analysis, IE interface customization, etc. As a summary, the author also reminds the reader to a little thing, if you don't want Bho to work, you can log out of the plugin, the following format: regsvr32 / u YourPath / YourBho.dll, or direct "Browser Helper Objects" directory directly in the registry The registered CLSID is deleted. Question] The thread has failed with the ADO to access the database? It is ok in the non-thread, but in the thread is not connected to the database, why? Answer] Initialization of COM in each sub-thread using ADO / Anti-initialization code // in the beginning of the threadcoinitialize ..... // in the end-point of the threadCounInitialize question] How to change with SQL statement ACCESS Dataset Table A field length? Answer] Conversion Size: Alter Table Your Table Alter Column Columm Name Your type Not NULL can also use a stupid method first DROP a column, then ALTER TABLENAEM Add Column Ask] A database program, with Access, but after storage data The MDB file is 10m, but the MDB file is still 10m after all of the data is removed. Why? How to change? Answer】 You should compress the MDB file after deleting the data: #import "c: / program files / common files / system / ado / msado15.dll" no_namespace rename ("eof", "adoeof") # import "C: / Program Files / Common Files / System / ADO / MSJRO.DLL"

Compressed file code: try {cstring cssourceConnection; cstring csdestConnection;

Coinitialize (NULL); CSSourceConnection.Format ("provider = microsoft.jet.Oledb.4.0; data source =% s; Jet OLEDB: Database Password =% s", "c: //tanyizhi.mdb", ""); CsdestConnection.Format ("provider = microsoft.jet.OLEDb.4.0; data source =% s; Jet OLEDB: Database Password =% s", "c: //tanyizhi_c.mdb", "" "; Jro :: jetEnginePtr Jet (__UUIDOF (JrouiD)); // ------------------------- IF "no_namespace" the -------- ------------------------ // ijetengineptr jet = null; //jet.createInstance (__uuidof(jetEngne)))

BeginWaitCursor (); jet-> CompactDatabase (csSourceConnection.AllocSysString (), csDestConnection.AllocSysString ()); EndWaitCursor (); CoUninitialize (); MessageBox ( "! Database Compact Successful ~", "Information", MB_ICONEXCLAMATION);} catch ( _COM_ERROR & E) {CString CSerror; cSerror = (lpctstr) E.DESCRIPTION (); MessageBox (CSERROR, "ERROR INFO", MB_ICONEXCLAMATION);}

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

New Post(0)