Mega Code Archive

 
Categories / Delphi / Examples
 

Date-time-day client-server with com

This example shows step by step how to make a COM Client-Server application that informs about current date, time and weekday. The Server will have three methods: GetDate, GetTime and GetWeekDay. The server could run local or remote. The Server: Select: New application. Put a Label on the Form and in the caption write: "DateTimeDay-server" or whatever you like. This form will be shown when the server executes. Select: New-ActiveX-Automation Object. Give the Object a CoClass name: MasDateTime Instancing: Multiple instance Threading model: Both Click OK. In the Project-Library wizard: Click on the interface: IMasDateTime Select: New - Method. Give the method a name: GetDate Select: Parameters - and in return type select: widestring (or BSTR* if you're using IDL. You can change this if you wan't to: Select Tools/Environmental options/Type Library and change Language.) Do the same with GetTime and GetWeekDay. Refresh implementation, and save the project as: MasTDD.dpr. If everything is OK, your project should consist of: Unit1 and Form1, Unit2 and the typelibrary: MasTDD_TLB. The typelibrary is where the description of your interface is, normally you don't have to change here. Unit2 is where the implementation is done. Take a look at Unit2. As you can see, the wizard has already made a skeleton for your methods. Let's fill it with some code: function TMasDateTime.GetDate: WideString; begin Result:= DateToStr(Now); end; function TMasDateTime.GetTime: WideString; begin Result:= TimeToStr(Now); end; function TMasDateTime.GetWeekDay: WideString; var Day: integer; begin Day:= DayOfTheWeek(Now); case Day of 1: Result:= 'Monday'; 2: Result:= 'Tuesday'; 3: Result:= 'Wednesday'; 4: Result:= 'Thursday'; 5: Result:= 'Friday'; 6: Result:= 'Saturday'; 7: Result:= 'Sunday'; end; end; Put: SysUtils, DateUtils in the Uses clause. Compile and save the project. The Client : Choose: New application. Put five buttons, a Label and an EditBox on the Form. Save the unit as Cl.pas and the project as Client.dpr Put: MASTDD_TLB in the upper uses clause: Put this code in the private clause: Server: IMasDateTime; Here's the rest of the code: implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage(Server.GetDate); end; procedure TForm1.Button4Click(Sender: TObject); begin Server:= CoMasDateTime.CreateRemote(Edit1.Text); end; procedure TForm1.Button2Click(Sender: TObject); begin ShowMessage(Server.GetTime); end; procedure TForm1.Button3Click(Sender: TObject); begin ShowMessage(Server.GetWeekDay); end; procedure TForm1.Button5Click(Sender: TObject); begin Server:= CoMasDateTime.Create; end; end.