作为一例,设想你有一MFC对话框--它通过一个多行的编辑框接受来自用户的数据-现在,你有一新的要求-显示一个只读编辑框,它将显示当前在该多行编辑框中文本的md5哈希结果。你的队友正在悲叹他们将必须花费几个小时钻研crypto API,而你的上司在担忧你们可能必须要买一个第三方加密库;那正是你在他们面前树立形象的时候,你宣布你将在15分钟内做完这项任务。下面是解决的办法:
添加一个新的编辑框到你的对话框资源中,并且添加相应的DDX变量。选择/clr编译模式并且添加下列代码到你的对话框的头文件中:
#include <msclr\auto_gcroot.h>
using namespace System::Security::Cryptography;
使用auto_gcroot模板来声明一个MD5CryptoServiceProvider成员:
protected:
msclr::auto_gcroot<MD5CryptoServiceProvider^> md5;
在OnInitDialog过程中,gcnew MD5CryptoServiceProvider成员。
md5 = gcnew MD5CryptoServiceProvider();
并且为多行编辑框添加一个EN_CHANGE处理器:
void CXxxxxxDlg::OnEnChangeEdit1()
{
using namespace System;
CString str;
m_mesgedit.GetWindowText(str);
array<Byte>^ data = gcnew array<Byte>(str.GetLength());
for(int i=0; i<str.GetLength(); i++)
data[i] = static_cast<Byte>(str[i]);
array<Byte>^ hash = md5->ComputeHash(data);
CString strhash;
for each(Byte b in hash)
{
str.Format(_T("%2X "),b);
strhash += str;
}
m_md5edit.SetWindowText(strhash);
}
这里使用了混合类型:一个本机Cdialog派生类,该类含有一个MD5CryptoServiceProvider成员(CLI类型)。你可以轻易地试验相反的情况(如早期的代码片断已显示的)——可以建立一个Windows表单应用程序而且可能想利用一个本机类库--这不成问题,使用上面定义的模板nativeroot即可。