是不是用MFC创建Automation组件时只能实现单接口,我试图加入第二个接口后,不但在Class View里看不见所有接口,而且第二个接口也无法注

cygroup 2002-05-14 10:18:00
是不是用MFC创建Automation组件时只能实现单接口,我试图加入第二个接口后,不但在Class View里看不见所有接口,而且第二个接口也无法注册到注册表中,真是奇怪啊?
...全文
42 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
cygroup 2002-05-14
  • 打赏
  • 举报
回复
自动化组件啊
fireflyxx 2002-05-14
  • 打赏
  • 举报
回复
什么是Automation哦??
主要介绍如何开发一个ActiveX控件,提供接口,与相应事件挂钩。文中涉及到VARIANT,SAFEARRAY,BSTR的详细使用方法。 另外还提供了WinSock的详细开发步骤,以及如何响应网络超,网络断开的事件方法以及在VC,VB调用该控件的方法。 一、MFC ActiveX控件开发步骤(VC 6.0): New->Projects->MFC ActiveX ControlWizard,然后输入MFCWinSock工程名。如下图: 图一 创建工程 一路狂按Next,直至Finsh出现,再按下OK,如下图:     图二 创建完成 二、架设Socket环境: 首先在StdAfx.h文件中加入下面这句代码: #include // MFC socket extensions 打开MFCWinSock.cpp文件,添加代码,看起来如下: //////////////////////////////////////////////////////////////////////////// // CMFCWinSockApp::InitInstance - DLL initialization BOOL CMFCWinSockApp::InitInstance() { BOOL bInit = COleControlModule::InitInstance(); if (bInit) { // TODO: Add your own module initialization code here. if (!AfxSocketInit()) { AfxMessageBox("无法初始化Socket,请检查!"); return FALSE; } WSADATA wsaData; WORD wVersion = MAKEWORD(1, 1);//设定为Winsock 1.1版 int errCode; errCode = WSAStartup(wVersion, &wsaData);//启动Socket服务 if (errCode) { AfxMessageBox("无法找到可以使用的 WSOCK32.DLL"); return FALSE; } } return bInit; } //////////////////////////////////////////////////////////////////////////// // CMFCWinSockApp::ExitInstance - DLL termination int CMFCWinSockApp::ExitInstance() { // TODO: Add your own module termination code here. WSACleanup();//结束网络服务 return COleControlModule::ExitInstance(); } 三,提供控件接口和事件 在MFCWinSockCtl.cpp加入如下代码: #ifndef WM_MYWINSOCK #define WM_MYWINSOCK WM_USER+1888 #endif View->ClassWizard->Automation->Add Method…如下图: 图三 创建接口 这个候,我们为这个控件添加了一个Connect()的接口,出于通用性,安全性和扩展性的考虑,我们采用了VARIANT类型的参数, 很多人可能都不太了解该类型,又或者有接触过,但被吓怕了,那么我们来看清它的本来面目: struct tagVARIANT { union { struct __tagVARIANT { VARTYPE vt; WORD wReserved1; WORD wReserved2; WORD wReserved3; union { LONG lVal; BYTE bVal; SHORT iVal; FLOAT fltVal; DOUBLE dblVal; VARIANT_BOOL boolVal; _VARIANT_BOOL bool; SCODE scode; CY cyVal; DATE date; BSTR bstrVal; IUnknown __RPC_FAR *punkVal; IDispatch __RPC_FAR *pdispVal; SAFEARRAY __RPC_FAR *parray; BYTE __RPC_FAR *pbVal; SHORT __RPC_FAR *piVal; LONG __RPC_FAR *plVal; FLOAT __RPC_FAR *pfltVal; DOUBLE __RPC_FAR *pdblVal; VARIANT_BOOL __RPC_FAR *pboolVal; _VARIANT_BOOL __RPC_FAR *pbool; SCODE __RPC_FAR *pscode; CY __RPC_FAR *pcyVal; DATE __RPC_FAR *pdate; BSTR __RPC_FAR *pbstrVal; IUnknown __RPC_FAR *__RPC_FAR *ppunkVal; IDispatch __RPC_FAR *__RPC_FAR *ppdispVal; SAFEARRAY __RPC_FAR *__RPC_FAR *pparray; VARIANT __RPC_FAR *pvarVal; PVOID byref; CHAR cVal; USHORT uiVal; ULONG ulVal; INT intVal; UINT uintVal; DECIMAL __RPC_FAR *pdecVal; CHAR __RPC_FAR *pcVal; USHORT __RPC_FAR *puiVal; ULONG __RPC_FAR *pulVal; INT __RPC_FAR *pintVal; UINT __RPC_FAR *puintVal; struct __tagBRECORD { PVOID pvRecord; IRecordInfo __RPC_FAR *pRecInfo; } __VARIANT_NAME_4; } __VARIANT_NAME_3; } __VARIANT_NAME_2; DECIMAL decVal; } __VARIANT_NAME_1; }; 它先是一个结构体,面有一个重要成员VARTYPE vt;vt即是指明当前的数据类型,比如整型或者字符型,当指明vt后, 后面看到各种变量类型包括在一个联合体当中,也就是说指明vt后,你只能使用对应的其中之一变量类型。看着这众多的各种不同 类型变量集中在一起,确实让人吓了一跳,但细细看来,大多数变量跟我们平的用法相似。值得一提的是SAFEARRAY __RPC_FAR *parray; 也许有很多人还没有接触过SAFEARRAY类型的变量,SAFEARRAY实际上也是一个结构,大家可以参考MSDN,我也将在后面介绍它的具体使用方法。 用同样的方法创建DisConnect()接口 创建两个事件,FireCloseWinsock()响应网络断开事件,FireRecvSockEvent()响应网络有数据到达的事件。创建方法如下图: 图四 创建事件 重载控件消息处理函数WindowProc(),在View->ClassWizard中打开类向导,在消息映射中找到WindowProc,如下图: 图五 重载WindowProc() 四、编写代码 编写VariantToLong()转换函数,该函数代码如下: //类型转换,将VARIANT类型转换成Long类型 long CMFCWinSockCtrl::VariantToLong(const VARIANT &var) { long r; switch(var.vt) { case VT_UI2://USHORT r = var.uiVal; break; case VT_UI4://ULONG r = var.ulVal; break; case VT_INT://INT r = var.intVal; break; case VT_UINT://UINT r = var.uintVal; break; case VT_I4://LONG r = var.lVal; break; case VT_UI1://BYTE r = var.bVal; break; case VT_I2://SHORT r = var.iVal; break; case VT_R4://FLOAT r = (long)var.fltVal; break; case VT_R8://DOUBLE r = (long)var.dblVal; break; default: r = -1;//无法转换该值 break; } return r; } 大家可以看到,该函数将最基本的若干中数据类型转换成了long类型,但VARIANT决不是个简的谱,我将在后面继续揭开它的神秘面纱. 编写我们刚才的接口Connect(),代码代码如下: 在MFCWinSockCtrl.h中加入 SOCKET OnlySock;//建立的唯一Socket,不允许重复建立多个 bool isOnlyConnect;//是否建立了连接 然后再编写Connect(),看起来如下: BOOL CMFCWinSockCtrl::Connect(const VARIANT FAR& RemoteHost, const VARIANT FAR& RemotePort) { // TODO: Add your dispatch handler code here if(isOnlyConnect)//该连接已建立,还没有断开 return FALSE; CString IPAddress; int Port;//转换成整型的端口 switch(RemoteHost.vt) { case VT_BSTR://字符串型 IPAddress = CString(RemoteHost.bstrVal); break; case VT_BYREF|VT_I1://CHAR * IPAddress.Format("%s",RemoteHost.pcVal);//RemoteHost.pbstrVal); break; default: IPAddress = ""; return FALSE; } Port = VariantToLong(RemotePort);//我们编写的一个VARIANT转换成long类型的函数 if(Port<=0) return FALSE; _TCHAR *ip = 0; struct hostent *host = 0; struct sockaddr_in addr; ULONG dotIP = inet_addr(IPAddress); OnlySock = socket(AF_INET, SOCK_STREAM, 0); // 判断是否为点IP地址格式 if (OnlySock == INVALID_SOCKET) { shutdown(OnlySock, 0x02); closesocket(OnlySock);//释放占有的SOCK资源 return FALSE; } memset(&addr, 0, sizeof(struct sockaddr_in)); // 设定 SOCKADDR_IN 结构的内容 // 如果通讯协议是选择IP Protocol,那此值固定为AF_INET // AF_INET 与 PF_INET 这两个常量值相同 addr.sin_family = AF_INET; addr.sin_port = htons(Port); addr.sin_addr.S_un.S_addr = dotIP; if (dotIP == INADDR_NONE) { host = gethostbyname(IPAddress); if (!host) { shutdown(OnlySock, 0x02); closesocket(OnlySock);//释放占有的SOCK资源 return FALSE; }; ip = inet_ntoa(*(struct in_addr*)(*host->h_addr_list)); addr.sin_addr.S_un.S_addr = inet_addr(ip); } //开始连线 if (connect(OnlySock, (LPSOCKADDR)&addr, sizeof(SOCKADDR))) { shutdown(OnlySock, 0x02); closesocket(OnlySock);//释放占有的SOCK资源 return FALSE; } int iError = WSAAsyncSelect(OnlySock, m_hWnd,WM_MYWINSOCK, FD_READ|FD_CLOSE); //只对网络断开和数据到达通知感兴趣 if(iError == SOCKET_ERROR)//无法绑定Winsock的事件通知 { shutdown(OnlySock, 0x02); closesocket(OnlySock);//释放占有的SOCK资源 return FALSE; } isOnlyConnect = true; return TRUE; } 有必要提一下WSAAsyncSelect(),这接收网络数据到达和断开的两个消息,我们收到WM_MYWINSOCK消息将处理该消息并作为事件传送给调用者. 第二个参数,窗口句柄,我们传送了m_hWnd,这是因为MFC ActiveX也属于一个窗口,并且是可见的,因此可以成功。 编写WindowProc(),代码看起来如下: LRESULT CMFCWinSockCtrl::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { // TODO: Add your specialized code here and/or call the base class switch(message) { case WM_MYWINSOCK://响应自定义的消息 switch(WSAGETSELECTEVENT(lParam)) { case FD_READ://有新数据到达 FireRecvSockEvent(); break; case FD_CLOSE://对方已断掉当前连接 FireCloseWinsock(); break; } break; default: break; } return COleControl::WindowProc(message, wParam, lParam); } 本部分结束语: 好了,现在一个可以运行的控件已经完成,面提供有Connect()和DisConnect()接口,和RecvSockEvent()及CloseWinsock()事件。以及WinSock的使用方法。 在下一部分(高级篇)将讲解两个重要接口SendData()和GetData(),下期内容如下: long SendData(const VARIANT FAR& Data, const VARIANT FAR& DataType,const VARIANT FAR& DataLength, const VARIANT FAR& TimeOut) long GetData(VARIANT FAR* Data, const VARIANT FAR& DataType, const VARIANT FAR& DataMaxLength, const VARIANT FAR& TimeOut) VARIANT和SAFEARRAY的复杂用法。 控件开发出来后在VC和VB环境下的使用方法。 声明: 部分资料来源于网络,本文所用的所有源代码仅供非商业用途,并请保留原版权,否则后果自负! 欢迎大家拍砖,或指正不足的地方,一起探导更好的方法。 欢迎访问www.59186618.com,感谢您的支持!
Introduction Like many of my colleagues in this industry, I learned Windows programming from Charles Petzold's Programming Windows—a classic programming text that is the bible to an entire generation of Windows programmers. When I set out to become an MFC programmer in 1994, I went shopping for an MFC equivalent to Programming Windows. After searching in vain for such a book and spending a year learning MFC the old-fashioned way, I decided to write one myself. It's the book you hold in your hands. And it's the book I would like to have had when I was learning to program Windows the MFC way. MFC, as you probably already know, is Microsoft's C++ class library for Windows programming. Programming Windows with MFC isn't a book about C++; rather, it's a book about writing 32-bit Windows applications in C++ using MFC rather than the Windows API as the chief means of accessing the operating system's essential features and services. It was written with two kinds of people in mind: Windows API programmers who want to learn MFC Programmers who have never before programmed Windows Whichever camp you fall into, I assume that you know the C++ programming language already and are comfortable with basic C++ idioms such as derived classes and virtual functions. If these assumptions are true, you're ready to begin climbing the hill that is MFC programming. Even veteran Windows programmers frequently find MFC code confusing the first time they see it, in part because of the presence of code created by the MFC code-generating wizards in Visual C++ and in part because of the countless lines of code hidden away in MFC classes such as CFrameWnd, CDocument, and CView. That's why this book takes a rather unusual approach to teaching MFC. It begins by having you write MFC code by hand (without the wizards) and by utilizing MFC 1.0-style application architectures—that is, applications that use neither documents nor views. Only after you've mastered the fundamentals and become acquainted with basic MFC classes such as CWnd and CWinApp do I introduce the wizards and teach you how to take advantage of MFC's document/view architecture. Along the way, you build a understanding from the ground up of the message-oriented nature of Windows and of key components of Windows itself, such as the Graphics Device Interface (GDI). I believe that this approach makes learning MFC not only less intimidating, but also more enjoyable. I think that you'll agree once you've worked your way through the book and can look back on the learning experience from the standpoint of a knowledgeable Windows programmer. Programming Windows with MFC is divided into four parts. Part I introduces the core tenets of MFC and Windows programming, beginning with a simple "Hello, MFC" application and introducing, one by one, menus, controls, dialog boxes, and other application building blocks. Part II builds on the foundation laid in Part I with a detailed look at the document/view architecture. In particular, Chapters 9, 10, and 11 reveal much of the "magic" behind documents and views and explain not only how to write basic document/view applications but also how to implement some not so basic features such as split-window views of a document and print previews. Part III covers some of the more advanced features of Windows and MFC—features such as color palettes, bitmap handling, and multiple threads of execution. In Part IV, you'll learn how MFC wraps its arms around COM, OLE, and ActiveX and how to write COM-enabled applications and software components. By the time you're finished with Chapter 21, you'll be well versed in the art of 32-bit Windows programming using MFC. And you'll have prodigious amounts of sample code to draw from when it's time to strike out on your own and write your first great Windows application. What's New in the Second Edition Those of you who read the first edition of this book will notice two rather obvious changes in the second edition. First, this edition contains seven new chapters. One is devoted to the MFC view classes; another covers the MFC collection classes; one introduces MFC file I/O and serialization mechanisms; and four cover the relationship between MFC and COM. MFC is not the general-purpose COM framework that the Active Template Library (ATL) is, but MFC makes certain types of COM programming exceptionally easy. For example, MFC greatly simplifies the task of writing ActiveX controls, and it makes writing Automation servers—programs that use COM to expose their functionality to scripting clients—a breeze. The second major change in this edition has to do with wizards. The first edition didn't cover the MFC wizards at all. The second edition uses hand-generated code in Chapters 1 through 3 but then shifts gears and begins using AppWizard and ClassWizard in Chapter 4. Why the change of heart? I still believe that code-generating wizards are an impediment to learning and should be used only by knowledgeable programmers, but I've also come to realize that in the real world, MFC programmers use the wizards. For certain tasks—writing ActiveX controls, for example—it doesn't make sense not to use the wizards. So after much deliberation, I decided I would be remiss not to cover them. Despite the new material regarding wizards, however, this is not—and never will be—a book about clicking buttons in AppWizard. After introducing a fundamental skill, such as how to write a message handler with ClassWizard, I thereafter let the source code do the talking and assume that you can figure out how the source code was created. Keep in mind that the wizards never do anything you can't do yourself, so it's perfectly feasible to type in every source code listing by hand if you'd like to. The downside to using wizards in a book that teaches MFC programming is that they produce code that isn't fit to publish. The first edition of this book included printed listings for each and every source code file. This one does not. It contains printed copies of relevant source code files and provides the others on CD. Why? Because printing a source code file that's 50 percent meat and 50 percent fat adds bulk to a book without adding content. Some of the code produced by the MFC AppWizard in Visual C++ 6.0 won't even compile. (For details, see Chapter 4.) I'm not very proud of the parts of my book that the wizards created, because those portions are littered with arbitrary blank lines, comments that lack consistent style, and unnecessary functions. For someone who takes pride in writing concise, readable sample code, wizard output is a bitter pill to swallow. Nevertheless, wizards represent the new world order in Windows programming, and they're something that you, I, and everyone else must get used to. It's a shame that the Visual C++ team won't give us real wizards to play with instead of the toys that they pass off as wizards today. Until they do, we must make do with what we have. What's On the CD The CD that accompanies this book contains source code and executables for all the sample programs presented in the book. All samples were written and compiled with Visual C++ 6.0 and MFC 6.0 and tested on various Win32 platforms. Unless otherwise noted, all are compatible with Windows 98, Windows NT 4.0, and Windows 2000. Most are also compatible with Windows 95 and Windows NT 3.51. You can copy the contents of the CD to your hard disk by running the setup program found in the CD's root directory, or you can retrieve the files directly from the CD's \Code directory. The \Code directory contains one subdirectory for each chapter of the book—Chap01, Chap02, and so on. Inside these subdirectories you'll find the sample programs. Each set of source code files is accompanied by a release-build EXE as well as a Visual C++ workspace (DSW) file that you can open with Visual C++'s Open Workspace command. From Me to You (and You to Me) From the day in 1995 when I began writing the first edition of Programming Windows with MFC, my goal has been to provide C++ programmers with the same kind of timeless, irreplaceable resource that Programming Windows is to C programmers. Whether I've achieved that goal, I'll let you be the judge. I want to know what you think about Programming Windows with MFC, and I particularly want to hear from you if you find mistakes. You can reach me by sending mail to jeffpro@msn.com or by visiting my Web site at www.prosise.com. At that site you'll find up-to-date information regarding the book, a list of errata, and information about other projects that I'm working on. Later this year, I plan to post a brand new chapter on MFC DLLs that you can read and comment on online. With the huge volume of computer books vying for buyers' attention in bookstores today, I know that you could have chosen any number of MFC books besides this one. I thank you for purchasing Programming Windows with MFC, and I sincerely hope you conclude that your money was well spent. Enjoy! Jeff Prosise
Contents Chapter 1: The Microsoft Developer Studio The Microsoft Developer Studio The Project Workspace Project Workspace Window Project Configurations Managing Complex Projects Project Settings Converting Projects Source Code Files Resource Scripts ResourceView Creating New Resources Identifying Resources Dialog Boxes String Tables Accelerator Tables Menus Icons, Bitmaps and Cursors Version Resources Custom Resources The Visual C++ Compiler Compiling on the Command Line The Foundation Classes MFC Source Code Header Files MFC Libraries Summary Chapter 2: The Wizards and The Gallery AppWizard Starting AppWizard Choosing Your Application's User Interface Selecting Database Support Adding Compound Document Support Embellishing Your User Interface Adding Advanced Features Miscellaneous Options Class Names One More Step Other Application Interfaces Choose Carefully! Compiling Your Application Precompiled Header Files ClassWizard Creating a New Class The .clw File The Browser Browser Files Browsing Shortcuts Components and Controls Gallery Summary Chapter 3: The Application Architecture Hierarchy The Application Framework Generating an Application with AppWizard Understanding the Generated Code CDocument and CView CWinApp CWinThread Locating Threads CCmdTarget Commands for Classes About Message Maps How are Message Maps Created? The BEGIN_MESSAGE_MAP() Macro Inside the Message Map Filling the Holes The END_MESSAGE_MAP() Macro Unfolding the Map There's No Sense of Obligation CObject Memory Management Debugging Support Serialization Run-time Type Information Your Own Classes and CObject The Big Picture: A New Life The WinMain() Function MFC's Message Pump Application Termination Summary Chapter 4: The Document/View Architecture Documents and Views Document/View Designs The Different Views Types of Document Document/View Consciousness What are Document Templates? CSingleDocTemplate S

16,551

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • AIGC Browser
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧