【 tulaoshi.com - Delphi 】
                             
                                 先行知识:Delphi/COM/OLEAutomation/SQLServer
  难度:★★☆☆☆
  在前几篇文章中我们已经讨论过关于VCL和OLE的知识。在这篇文章中我们将完成一个比较有实际意义的OLEAutomation服务器程序,最后我们把他们封装为Delphi中使用的VCL组件。
  首先我们来做一个实际的程序,在它没有变为服务器之前,这是个用来管理客户购买记录的程序(它自己与SQLServer连接),它可以录入和删除客户的购买记录并直观的显示出来,所有的数据都存放在SQLServer中。我们将它做为OLEAutomation出于这样一种考虑,假设我们是一家大型的供货公司,我们可能有很多系统需要使用这个客户购买记录程序并用它处理SQLServer中相应的数据,但我们不愿意每次都重复的编写同样的处理代码,我们更希望能把这个处理程序独立出来,并向其它程序提供服务。那么在下面的工作中我们完成了这个服务器程序,界面如下:(注意,这仅仅是一个例子,我们不评价其数据库设计的好坏J)  
  我们不过多的讨论这个程序的代码(因为这和开发一般的程序没有任何不同,你可以按照最后的地址给我来信索取这篇文章的全部代码)。然后我们来把它变为一个服务器。选择FileàNewàOthersàActiveXàAutomationObject。接下来delphi为我们定义了类型库和实现文件,我们要做的只是在类型库中添加相应的我们要用到的服务器属性和事件。我们简单的给出定义这个OLEAutomation功能的接口(来自类型库所产生的ObjectPascal代码):  
  ICustFormOLE=interface(IDispatch)  
  ['{D7AE75F9-F838-4702-A8EB-EAD0EED242DE}']  
  functionGet_CustName:WideString;safecall;  
  procedureSet_CustName(constValue:WideString);safecall;  
  functionGet_ProductName:WideString;safecall;  
  procedureSet_ProductName(constValue:WideString);safecall;  
  functionGet_ProductNum:Integer;safecall;  
  procedureSet_ProductNum(Value:Integer);safecall;  
  functionGet_Remark:WideString;safecall;  
  procedureSet_Remark(constValue:WideString);safecall;  
  //下面的方法和属性都对应着原程序中相应的方法和属性  
  procedureAddToData;safecall;  
  procedureDelData;safecall;  
  propertyCustName:WideStringreadGet_CustNamewriteSet_CustName;  
  propertyProductName:WideStringreadGet_ProductNamewriteSet_ProductName;  
  propertyProductNum:IntegerreadGet_ProductNumwriteSet_ProductNum;  
  propertyRemark:WideStringreadGet_RemarkwriteSet_Remark;  
  end;  
 ICustFormOLEDisp=dispinterface  
  ['{D7AE75F9-F838-4702-A8EB-EAD0EED242DE}']  
  propertyCustName:WideStringdispid201;  
  propertyProductName:WideStringdispid202;  
  propertyProductNum:Integerdispid203;  
  propertyRemark:WideStringdispid204;  
  procedureAddToData;dispid205;  
  procedureDelData;dispid206;  
  end;  
  我们现在回到接口的实现文件,注意代码中的注释,事实上这段代码相当的简单:  
  unitCustOLEImpUnit;  
  {$WARNSYMBOL_PLATFORMOFF}  
  interface  
  uses  
  ComObj,ActiveX,CustViewOLE_TLB,StdVcl,windows;  
  type  
  TCustFormOLE=class(TAutoObject,ICustFormOLE)  
  //注意这里实现了我们在前面定义的ICustFormOLE接口  
  protected  
  functionGet_CustName:WideString;safecall;  
  functionGet_ProductName:WideString;safecall;  
  functionGet_ProductNum:Integer;safecall;  
  functionGet_Remark:WideString;safecall;  
  procedureAddToData;safecall;  
  procedureDelData;safecall;  
  procedureSet_CustName(constValue:WideString);safecall;  
  procedureSet_ProductName(constValue:WideString);safecall;  
  procedureSet_ProductNum(Value:Integer);safecall;  
  procedureSet_Remark(constValue:WideString);safecall;  
  end;  
  implementation  
  usesComServ,CustFormUnit;  
  functionTCustFormOLE.Get_CustName:WideString;  
  begin  
  result:=CustForm.CustomEdit.Text;  
  //可以看到,我们只是用了最初程序窗体的控件和属性,这里的接口实现相当于