What's new for MFC developers? (Zz)

Source: Internet
Author: User
Tags microsoft c

What's new for MFC developers? (Translation)

--------------------------------------------------------------------------------
Author: kamphkb Source: http://msdn.microsoft.com/msdnnews/2001/sept/vcnet/vcnet.asp
 
What's new for MFC developers?
By Anson Tsao and Walter Sullivan
By bar wanghai (kevin_kbh@21cn.com)
[Translator: due to the time relationship, I omitted some detailed translations, but I still clicked on them. If you are interested, you can continue. You can reprint it at will, but do not modify any text in this article. If you can, use mail to notify me when reprinting. Thank you! Anyone who wants to communicate with me is welcome!

There have been no major updates for MFC and ATL for three years. Under the Strong publicity of Microsoft. NET, the MFC and C ++ developers feel abandoned. But don't worry-in the coming Visual Studio. in. net, Visual C ++ developers not only get a brand new IDE that is comprehensive and closely related to server development, but also greatly improved the C ++ compiler, MFC and ATL have also gained new important features. There is a clear message that MFC will still be on all Windows platforms, with a large number of customer programs, the best and longest framework. In this article, we will show you the new features that can be used in your MFC program.

· Use the new mfc dll (mfc70.dll), which is no longer compatible with mfc42.dll, but your source program remains compatible (Message ing is more secure, so it may cause some code violations ).

· The combination of MFC and ATL is closer. Some common classes such as cstring can be used by both libraries at the same time.

· The header file is synchronized with the new platform SDK and supports new UI features in 2 K and XP, such as themes and manifest

Resources, active accessibility, and the new general dialog box.

· Added a number of UI classes, including DHTML-supported dialog boxes and cimage that supports bitmap extension.

· New Tool classes can be used in MFC and ATL, such as regular expressions, counters, and security.

· The MFC Application strongly supports Web Services. Compile web services and applications in the ATL server class.

· Using the new ole db feature makes it easier to access the database efficiently than it is now.

· STL updated

Can integrated MFC and ATL use cstring in ATL or Use ATL in large MFC to implement COM objects? Now, we can. In MFC 7. There are many tool classes in 0 that can be shared between ATL and MFC: cstring, cpoint, crect, csize and cimage. In addition, ATL can be used without the support of MFC. Cstring has been completely rewritten and is now based on the template class cstringt <>. It supports various character types (char, wchar_t, tchar) and is based on CRT. You can also manage the memory allocation in cstring.
For example
Typedef struct my_chr {
Unsigned int;
Unsigned int B;
Unsigned int C;
} My_chr;

Cstringt my_str;
...
]

Mfc7.0 adds a new string class called cfixedstringt <>. This fixed-length string provides a user-defined length method, eliminating the need for additional memory before consuming the internal space. Cfixedstringt is very efficient when used for stack-based variables or elements in the combined container. It significantly reduces heap-based allocation.
[Translator: I am confused here, too. please correct me. The original article is as follows:
Cfixedstringt's are very efficient when used as stack-based variables or as keys in associativecontainers, dramatically cing the number of heap-based allocations .]

The following example creates an instance with 1024 characters:

// Allocating 1024 character internal buffer
Cfixedstringt <cstring, 1024> string;

New UI features and upgrades
Mfc7.0 provides DHTML Dialog Box support, a set of DHTML editor classes, a new graphic API (GDI +), updated bitmap support (cimage), and added a Common Dialog box packaging class (clinkctrl ), the update control and dialog box support 2 K and XP, enhance the ActiveX control container and improve the type security of message ing. Let's take a look at it one by one.

DHTML dialog box and DHTML editor class
The DHTML dialog box brings a variety of HTML user interfaces to desktop applications. Now, your desktop app has a stylish graphical interface that is not readily interactive with common web applications. Mfc7.0 provides cdhtmldialog and cmultipagedhtmldialog to support DHTML. The DHTML dialog box displays HTML pages from resource files or any valid URLs. If you have used chtmlview, you will know that you need to use ihtmldocument2 to obtain and set HTML elements, and it is very painful to process HTML events. Cdhtmldialog greatly simplifies this interaction and uses a set of extended macros and DHTML event ing similar to DDX. The ddx_dhtml _ macro and the traditional DDX _ macro are also used in the dodataexchange function. It allows you to obtain and set attributes of various HTML elements. For example, the value of the check box bound to ddx_dhtml_checkbox and the value of ddx_dhtml_elementinnerhtml are used to set and obtain the HTML of an element. To bind an HTML element to DDX, you must have an 'id = 'attribute for this element, as shown in the following code:

Filename:

Read-Only

Void cpropertiesdlg: dodataexchange (cdataexchange * PDX ){
Cdhtmldialog: dodataexchange (PDX );
// {Afx_data_map (cpropertiesdlg)
//} Afx_data_map
Ddx_dhtml_elementinnertext (PDX, _ T ("FILENAME"), m_strfilename );
Ddx_dhtml_checkbox (PDX, _ T ("readonly"), m_nreadonly );}
To respond to HTML control events, You have to define a DHTML event map:

Begin_dhtml_event_map (cdhtmlexploredlg)
Dhtml_event_onclick (_ T ("Browse"), onbrowse)
Dhtml_event_class (dispid_htmlelementevents_onmouseover,
T ("comment"), onmouseoverelement)
End_dhtml_event_map ()

These event mappings are similar to the MFC style, including the definition of declare_dhtml_event_map and the definition between begin_dhtml_event_map and end_dhtml_event_map. Cmultipagedhtmldialog is suitable for guiding the dialog box related to the property page. It can load multiple pages in a dialog box and use internal event ing to respond to events. This new version also provides the wysiwyg dhtml editor. This means that adjusting an HTML element in your program is no more difficult than adjusting a text control. Similar to mfc6.0's support for rich edit controls, mfc7.0 provides chtmleditctrl and similar document view classes: chtmleditview/chtmleditdoc. However, you still need to adjust the UI elements, such as font, style, color, and so on.

GDI +
GDI + is a new graphics subsystem that provides a complete set of graphic APIs to render 2D images, images, and text. It is the only API in. net, but in C ++, it supplements the rendering capability of GDI. Using GDI +, you can obtain: stronger 2D plotting, alpha channel support, General coordinate conversion and floating point support, as well as gradient brushes, cardinal splines, scalable regions, and new programming modes. GDI + is released as a C-style API. Although a set of C ++ classes package it, it is not supported by MFC but used in. net. Use GDI +, use gdiplus. H, and link gdiplus. Lib. You must also initialize this library before use. GDI + is a part of XP. To use it on 98, me, NT4.0, and 2 K, copy gdiplus. DLL to the corresponding directory. GDI + uses a different programming model than GDI. The pen or brush must be passed in each drawing command in GDI +. The graphic element does not work with the pen and the arrow; the border outline and fill are split into different functions for implementation (such as drawrectangle and fillrectangle ). The following example shows how to draw a rectangle (3.5 inch x 4.4 inch ).

Using namespace gdiplus;
Void cmyview: ondraw (CDC * thedc)
{
Graphics graphics (* thedc );
Pen (color (128,255, 0, 0), 2.0); // Alpha value set
// Realworld units
Graphics. setpageunit (unitinch );
// Floating Point Coordinates
Graphics. drawrectangle (& pen, rectf (0.0f, 0.0f, 3.5f, 4.4f ));
}

Use cimage to manage bitmap
The long-awaited bitmap support has finally been implemented in this version. Cimage allows you to read and store image files in JPEG, GIF, BMP, and PNG formats. However, some functions are not supported by the old system (such as 95), and some functions have different implementations on different operating systems. Cimage can

In MFC and
Used in ATL. It also encapsulates the dib function and allows you to directly operate pixel points. Let's take a look at what cimage provides:

· Alpha Pixel blending transparency and translucent Effect

· Plgblt can map a rectangle to a parallelogram at will.

· Transparentblt allows transparent operations based on a specified color

· Maskblt can mix two images to an output device.

· Cimage: getdc can draw a picture directly to a bitmap.

The following is an example:

Cimage image;
Image. Load ("test.gif ");
Cbitmap * pbitmap = cbitmap: fromhandle (image. m_hbitmap );

Clinkctrl Common Dialog Box class
Clinkctrl encapsulates the syslink control, which can be easily placed on windows, but only used on XP. It supports one or more hyperlinks. You can process the nm_click and nm_return message response click events in on1_y.

2 K and XP support
All common controls, cchecklistbox, and file processing and printing are updated to support 2 K and XP. The cwnd method is also updated to support new features such as layered windows and animation windows ). Clistview supports tile style in XP. Mfc7.0 supports XP themes ). Cwnd now supports active accessibility. The new cprintdialogex updates the Print dialog box.

Enhanced ActiveX container
Mfc7.0 and ATL support windowless ActiveX and the container can be rewritten. Currently, MFC also enjoys the same container optimization as Visual Basic. Now you can rewrite the colecontrolsite to increase the container behavior of your own.

Type-safe message ing
Mfc7.0 enhances the verification of the return values of message processing functions. For example, if void instead of lresult is returned in OK, the compiler considers it an error.

All-in-One tools
New Tool classes include: Regular Expression class, 64-bit Date and Time Functions, set template class, security class, functions and classes for packaging CryptoAPI, macro and thread pool support for counting. We will give a brief introduction later.

Regular Expression class)
This template class is used for string query and comparison, and supports both MBCS and Unicode. There are two template classes: catlregexp and
Catlrematchcontext.
The following is an example:
Catlregexp <> re; // using the default character trait
Re. parse ("AB. d ");
Catlrematchcontext MC;
Re. Match ("ABCD", & Mc); // returns true, successful match
Re. Match ("bbcd", & Mc); // returns false, no match

64-bit Date and Time Functions
Your code may not have any millennial problems, but the standard C Runtime Library will go wrong after 19:14:07 on January 1, January 18, 2038. The new 64-bit day

The period time function can last until December 31, 3000.
Ctime, ctimespan, and C Runtime libraries are updated to support the _ int64 data type, including ctimespan: getdays64,
Ctimespan: gettotalhours64, ctimespan: gethours64, ctimespan: serialize64,
Ctime: gettime64, and ctime: serialize64; and _ ctime64, _ wctime64, _ ftime64, _ futime64, _ gmtime64,
_ Localtime64, _ time64, _ utime64, _ wutime64; _ findfirst64, _ wfindfirst64, _ findnext64, _ wfindnext64; and _ stat64, and _ wstat64.

ATL collection class and matrix class
Atl7.0 provides five new collection classes: atlarray, catllist, catlmap, crbmap, and crbmultimap. They can better support non-standard data types. Use classes that can describe the quality of elements. These classes describe how elements are copied, moved, and cleared. Cautoptrelementtraits, cautovectorptrelementtraits, ccomqiptrelementtraits,

Cstringelementtraits,
And so on. These ATL collection classes do not support serialization. To use them, you must specify the element type and the quality of the description element at the same time:
Crbmap <cstring, cstringelementtraits, cautoptr, cautoptrelementtraits>; a dictionary is defined here to map cstring to the automatic pointer of cmyobject. The elements of cmyobject are automatically destroyed when the collection class is destroyed.

Security
Security class encapsulates all NT security mechanisms. Atl7.0 packed:

· Access Control List (CaCl)

· Any Access Control List (cdacl)

· System access control list ()

· Sid Security ID (csid)

· Access Node (caccesstoken)

· Ctokengroups)

· Ctokenprivileges)

· Security description (csecuritydesc)

· Csecurityattributes)

· Some global functions

Unfortunately, ATL 7.0 does not provide an advanced security model. You still need to have an in-depth understanding of Win32 security mechanisms.

Cryptographic class
The cryptographic class encapsulates the Win32 CryptoAPI and provides encryption, decoding, hash, digital signature, and key management.

That's it! If you don't want to use C ++ attributes, there are corresponding classes and macros that you can use instead. you shoshould also be aware that setting counters to specific values is generally safe without having to worry about thread synchronization, but specify Ming calculations on the counters, such as incrementing or decrementing, requires the use of atomic operations such as interlockedincrement or synchronization using critical sections.

Performance counters)
To use performance testing in your program, you need to implement three types of objects: performance monitoring management objects, performance objects and performance testers. The following shows how to define performance monitoring management objects:

[Perfmon (name = "myapplication", register = true)]
Class cmyapplicationperfmon
{
};

Then you can use the performance tester:

Void setcounter (ulong value)
{
If (g_pstatsobject)
G_pstatsobject-> samplecounter = value;
}

You don't have to worry about thread synchronization when using them, but the tester needs atomic operations, such as interlockedincrement or synchronization.

Thread Pool
The MFC 7.0 thread pool is based on the nt I/O completion port. Cthreadpool is a template class that supports working threads. When a thread can work, the execution function of your working thread will be called. The query and execution of working threads follow the FIFO (first-in-first-out) principle. The thread pool must be used:

· Initialize one thread at a time

· Threads executed in the Request queue one by one

· One thread is destroyed at a time

· Declare a requesttype typedef in the working Thread class, which will be processed during execution

 

Requesttype is an opaque type and cannot be greater than sizeof (ulong_ptr) (that is, 32-bit on X86 PC ), therefore, you cannot use a class instance or a large primitive type (such as floating point ).
The following is an example:

Class cmyworker
{
Public:
Typedef cmydata * requesttype;
Bool initialize (void * initparam );
Void execute (cmydata * request, void * initparam, overlapped * poverlapped );
Void terminate (void * initparam );
};

The following describes how to initialize and query a task in the thread pool:

Cthreadpool <cmyworker> threadpool;

Threadpool. initialize ();
Threadpool. queuerequest (New cmydata ());
Threadpool. Shutdown (1000l );

Web Services, web applications, and network
Mfc7.0 supports Web service programs, compiling Web Services, and using the ATL server class to write web applications. In the following section, we will demonstrate how to access the Web Service and call the service. It also explains how to generate HTML and write it into istream, how to use the HTTP client, and how to use MFC to send mail.

To call the methods exposed by the web service, simply instantiate an instance of the proxy class and call its methods, just like a native C ++ class!

# Include "myservice. H"
???
Myservice: cmyservice service;
Hresult hR = service. mymethod (ccombstr (L "a parameter "));

Support Web Services in MFC
Unlike DCOM, Web services are easy to access through firewalls and provide a truly loose connection. Using Web Services is no more difficult than using # import. Use the command line program sproxy.exe to generate C ++ client code to access the Web service. The generated proxy class contains everything you need. The following is an example:

Sproxy/out: myservice. h
Http: // myserver/myservice. dll? Handler = genmyservicewsdl

To call a web service method, you only need to initialize this proxy class and directly call its method, just like a common C ++ class:

# Include "myservice. H"
...
Myservice: cmyservice service;
Hresult hR = service. mymethod (ccombstr (L "a parameter "));

HTML Builder
This function is supported by the chtmlgen class and template chtmlgenbase <>. Chtmlgen writes a full HTML file to istream. To use it, you only need to initialize it with an istream and call the corresponding method.

Chtmlgen out;
Out. initialize (astream );
Out.html ();
Out. Head ();
Out. Title ("test html ");
Out. headend ();
Out. Body ();
Out. A ("http://www.microsoft.com", "Microsoft ");
Out. bodyend ();
Out.html end ();

HTTP customer
Catlhttpclient is a lightweight HTTP client class that can send requests and receive responses. It supports proxy and various verifications (currently, basic and NTLM are supported ). Catlhttpclient sends requests synchronously, so it is best to place the requests in multiple threads.

Catlhttpclient client;
Client. navigate (_ T (http://www.microsoft.com ));
Cstring contenttype;
Client. getheadervalue (_ T ("Content-Type"), contenttype );
Byte * pbody = client. getbody ();

Cbasicauthobject and cntlmauthobject support verification. The following is an example:

Cntlmauthobject ntlmauth;
Client. addauthobject (_ T ("NTLM"), & ntlmauth );

 

SMTP supports MIME-encoded messages
SMTP support removes the need for other mail client support. Csmtpconnection directly connects to an SMTP server and sends a mime-encoded mail. Cmimemessage can add attachments, raw data, and other mime-encoded messages to mail. This example shows how to construct a mime message:

Cmimemessage message;
Message. setsender (_ T ("someone@microsoft.com "));
Message. addreceipient (receipient );
Message. setsubject (_ T ("A Test message "));
Message. addtext (_ T ("This Is A Test message "));
Csmtpconnection connection;
Connection. Connect (somesmtpserver );
Connection. sendmessage (Message );

Efficient ole db database access
[Translator: This piece of nonsense is really much. In short, it is easier to program than before. However, the database is always complicated and it cannot be explained in a short period. Lazy without translation :)]

Updated STL
The added hash_map, hash_multimap, and hash_set classes are based on the new hash-table-based extension class. They are similar to STD: map, STD: multimap and STD: set, but have very different performance characteristics. Hash-table-based is much faster than binary tree-based in search. Unlike map and set, the hash class is not ordered. The new version of STL also eliminates the famous multi-thread problem of basic_string. No longer use counters, but strictly use copies. Finally, STL has better DLL support. It is no longer a local static data member.

Conclusion
Visual Studio. net is a giant step forward for enhancing programmer productivity, and the Microsoft. net initiative will likely change the programming landscape in the coming years. with this release of Visual C ++, MFC 7.0 has been updated to live in this new world of Web Services, while gaining better C ++ standard compliance, full integration with ATL, and numerous enhancements to UI and Utility Classes. best of all, these new features can be added to your existing MFC applications.

Summary
MFC has been closer to the C ++ standard, fully integrated with ATL, and greatly enhanced in terms of UI and tools. It is best to add these new features to existing code.

About Author:

Anson Tsao has 12 years of industry experience and is engaged in the development of large-scale windows and C ++. Recently, he joined the Microsoft Visual C ++ libraries team.

Walter Sullivan has been working in Microsoft for 11 years and spends almost all his time on the Visual C ++ product team. He now leads Microsoft C ++ class libraries program management.

About Translator
Just a C ++ fans. Call me Kamp. I care code performance before, and now care the performance of a certain project as a whole.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.