Document not found! Please try again

Creating OLE Servers in Visual Basic to Simplify Windows Function ...

12 downloads 109316 Views 102KB Size Report
Jul 7, 1995 - have equivalent knowledge in making Windows API calls from Visual ... The Win32® Software Development Kit (SDK) and Win16 SDK are ...
Creating OLE Servers in Visual Basic to Simplify Windows Function Calls (Archived Vi...

Page 1 of 8

MSDN H om e > MSDN Libra ry Archiv e >

Archived content. No warranty is made as to techni cal accuracy. Cont ent may c on tain URLs t hat were vali d when origin ally publis hed, but now link to sit es or pages that no l on ger exist. Vis ual Basi c 4.0 Techni cal Artic les

Creating OLE Servers in Visual Basic to Simplify Windows Function Calls Ken Las sesen Mi cros oft D eveloper Network Technology Group Jul y 7, 19 95

Abstract This art icle explains h ow to bui ld both 16 -bit and 32 -bit out -of -process OLE s ervers i n Vis ual Basi c ® version 4.0, servers t hat can encapsu late common Mi cros oft ® Windows ® app licati on programmi ng interfac e (API) calls or fu nctions in third -party dynamic -link libraries (DLLs ). Creati ng an OLE server wrapper around Wi ndows calls permits 16 -bit applic ations to c al l 32 -bit API functi ons and 32-bit applic ations to c al l 16 -bit API functi ons. The API c all is als o simplifi ed by:  The addi tion of named properties to the API call.  The removal of memory and struct ure allocat ions from your project.  The removal of API declarations from your project.

The reader is ass umed to have pass ed Mi crosoft Cert ificati on i n Microsoft Vis ual Bas ic for Win dows version 3.0 or have equivalent knowledge in making Wi ndows API c alls from Visual Basic .

The API Journey Continues This art icle describes how to buil d a s imple out -of-process OLE s erver in Visu al Basic ® that allows you to make app licati on programmi ng interfac e (API) calls us ing thi s OLE server's properties and methods i nstead of using Declare s tatements. The Win3 2® Software Development Kit (SDK) and Win16 SDK are proc ed ure -oriented and not ob ject -oriented th e way OLE servers are. I use OLE servers to place C-like calls out of si ght and to stop rewritin g the code t o make the same API calls c on stantl y.

8 /1

1 1 / 4

For mos t Micros oft® Office devel opers, th e most i mportant feature of an OLE server is th at wit h an out -of-process server (an exec utable), an appl icati on c an call a 16 -bit API from a 32-bit applic ation or c al l a 32-bit API from a 16bit applic ation with no diffic ulty. OLE will move the data ac ross process es au tomaticall y—no t hunking or determini ng the "bi tness" of the engine by the devel oper. (See my articl es list ed i n the "Bibl iography" secti on for furt her information on t his is sue.) A second feature of thi s OLE server i s the additi on of named properties for API arguments (and th e c hanging of some arguments to being optional ). A third featu re of t his OLE server is the abil ity to access the API c alls as cl as ses of fu ncti on s —classes t hat can reflect your view of API calls . Th e fourth feature of this OLE server is t he simple way it provides for ot her devel opers to leverage th e API knowledge of an expert . All of these features do come wi th the cost of sl ightl y sl ower execut ion of API c al ls and sl ightly great er use of memory.

0 0 2 s

t n

The OLE s erver implements an app roach si milar to t he on e I used in my earlier artic le "Creati ng Useful Native Vi sual Basic an d Mi cros oft Acc es s Fu nction s." Th ere is no need for the appli cation to alloc ate space for the API -call arguments bec au se the OLE server will al locate the space for t he arguments and Visu al Basic for Appl icati ons, Acc es s Bas ic, and Vi sual Basic will release the space. This approach can als o b e us ed i n C lan guage as an al ternati ve to thunking .

e m e r i u q e R

Us ing an OLE server is a better approach for the 16 -bit/32 -bit int eroperabil ity probl ems than those desc ribed in my artic les "Porting Your 16-Bit Office-Based Solution s to 32-Bit Office" and "Corporate Developer's G uide to Offic e 95 API Issues." Th ere is no need for the solu tion code to determi ne the "bi tness" of the applic at ion engine. Creat ing an OLE server i s so easy in Vi sual Basic that i t shoul d b e tau ght in every beginni ng Vi sual Bas ic cl as s!

http://msdn.microsoft.com/archive/en-us/dnarvb4/html/msdn_apiole.asp?frame=true

10/20/2007

Creating OLE Servers in Visual Basic to Simplify Windows Function Calls (Archived Vi...

Page 2 of 8

A Map for the Journey For an OLE s erver to be callabl e from b ot h 16 -bit and 32-bit applic ations, th e s erver must be ou t-of-process —that is, an exec utable (.E XE) file. This artic le wil l show you h ow to:  Creat e an i nvi sibl e OLE server in Visual Basic t hat can make an API call .  Us e t his OLE server from an Vi sual Bas ic for Applic ations product (Microsoft Excel) and from Microsoft Ac cess

version 2.0. Before proc eed ing too far, let's l ook at how our s olution c ode wil l change in appearan ce. Call ing the GetProfileString fun ction in Vis ual Basi c for Ap plicati ons has res ulted in c ode l ike t he fol lowi ng: REM Following line is needed ONCE in project Declare Function GetProfileString Lib "Kernel" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Integer) As Integer . . . Dim Buffer As String * 255,BufferLen As Integer, RC%, Default As String BufferLen=255 RC% = GetProfileString("TEST", "KEY", "", Buffer, BufferLen) If RC% > 0 Then TestKey$ = Left$(Buffer, RC%) Else TestKey$ = "" End If When an OLE s erver is u sed, the code becomes much si mp ler and much c learer: Dim WinIni As New MyWinAPI.WinINI . . . TestKey$=WinIni.Value(AppName:="TEST", KeyName:="KEY") MyWinAPI.WinINI i s the OLE server c lass us ed for API c al ls. Aft er you declare and create an i nstanc e of the OLE server, the server's Value propert y cal ls the approp riate API automatic ally. The use of n amed properti es makes the code easi er to read and und erstand. The OLE server contain s any n eeded decl arations or type libraries t o ac tually make the API call.

8 /1

1 1 / 4

So, how d o we make th is techn ol ogical miracle happen?

0 0 2 s

Creating an API OLE Server in Visual Basic

I wi ll st art by assumin g that you are an experienced programmer in Visu al Basi c 3.0 who has ju st opened up Vi sual Basic 4.0 Professi onal or Enterpri se Editi on an d t hat you have not h ad t ime to look at t he manu al s. I will go st ep b y step through the proc ess of buildi ng an out -of -process OLE s erver by buil ding a OLE server t hat has one class modu le, WinIni, and one sampl e property, Value. For further det ai ls on buil ding OLE servers, see the book Creat ing OLE Servers i n the Vi sual Bas ic 4.0 docu men tation.

t n

Foll ow thes e four steps to cons tru ct an invis ible OLE server i n Vis ual Bas ic:

e m e r i u q e R 1.

Creat e an OLE server project. (I us e t he 16-bit versi on of Visual Basic for this s amp le.)

2.

Creat e a Main s ubrout ine.

3.

Creat e a cl as s module for the properti es an d met hods.

4.

Creat e t he p ropert ies and methods in t his cl as s module of the OLE server.

Steps 3 and 4 may be repeated in one project as oft en as n eeded. Once the server's code is compl et ed, i t can be used as an OLE server.

http://msdn.microsoft.com/archive/en-us/dnarvb4/html/msdn_apiole.asp?frame=true

10/20/2007

Creating OLE Servers in Visual Basic to Simplify Windows Function Calls (Archived Vi...

Page 3 of 8

Creating an OLE Server Project The fi rst s tep is to creat e an OLE server project: 1.

Start a n ew project in Vi sual Basic 4.0.

2.

From t he T ool s menu, choose Opt ions, and then c lick the Project t ab.

3.

Select Sub Main in t he Startup Form lis t.

4.

Type MyWinAPI i n the Project Name text box. Th is is th e name of the OLE objec t.

5.

Type My First WINAPI OLE Server i n the Appl icati on D escription t ext box.

6.

Cli ck OLE Server in the St artMode grou p, and c lick OK. See Figure 1 .

1 1 / 4

Figure 1. The Options dialog box set for an OLE serv er project

Creating a Main Subroutine

8 /1

0 0 2 s

The s econd step is t o d el et e t he d efaul t Form1 and c reate a Main s ubrout ine. 1.

From t he Fil e menu, c hoose Remove Fil e.

2.

From t he Insert menu, choose Module.

3.

From t he Insert menu, choose Proc edu re. In th e Insert Procedure d ialog box, type Main i n the Name t ext box, click Sub in the Type grou p, c lick Publi c in the Scope group, and t hen clic k OK. See Figure 2.

t n

I wi ll leave this procedure empty so th at the execu table termin at es if direc tly execu ted. You may wish to i nsert an i nformative message box instead.

e m e r i u q e R

http://msdn.microsoft.com/archive/en-us/dnarvb4/html/msdn_apiole.asp?frame=true

10/20/2007

Creating OLE Servers in Visual Basic to Simplify Windows Function Calls (Archived Vi...

Page 4 of 8

Figure 2. Creating the Main subroutine

Creating a Class Module The t hird s tep is to create a cl ass module for th e properti es and met hods. 1.

From t he Insert menu, choose Class Module.

2.

Press F4 to disp lay t he Property Sheet.

3.

Type WinINI as t he Name propert y, set t he Instancing propert y to "2 - Creat able Mu ltiUse," and the Public propert y t o "True" as in Figu re 3.

4.

Clos e t he p ropert y s heet b y pressin g ALT+F4 .

8 /1

1 1 / 4

Figure 3. The property sheet of a class module

Creating the Properties and Methods

0 0 2 s

t n

e m e r i u q e R

Figure 4. Creating a new property in a class module The fourth st ep i s to create th e properti es an d met hods of the OLE server. The following process i s repeated as often as needed: 1.

From t he Insert menu, choose Proc edu re.

http://msdn.microsoft.com/archive/en-us/dnarvb4/html/msdn_apiole.asp?frame=true

10/20/2007

Creating OLE Servers in Visual Basic to Simplify Windows Function Calls (Archived Vi...

2.

Page 5 of 8

Type Value i n the Name t ext box, cl ick Propert y i n the Type group, cli ck Pu blic i n the Scop e group, and then click OK. See Figure 4. The foll owi ng code is the res ult of this process : Public Property Get Value() End Property Public Property Let Value(vNewValue) End Property

Note A prop erty can be on both t he l eft an d the righ t side of an equ al sign (that i s, you c an both as sign and read i ts values). A method is a procedure t hat can appear on ly on t he right s ide of an equ al sign. The default procedures for a property are shown above. Properties c an be Get or Let or both. For my example propert y, a st ring property, I wil l use both Get an d Let . Th e next st ep i s to put your c ode t o c all the API into th e procedures and add appropriate argument s. The names of th e arguments will appear in the Visual Basic for Appli cation Objec t Brows er, so I would recommen d droppin g Hungari an notation prefixes an d carefull y ch oos ing the names of all arguments. Do not c hange the name of vNewValue—jus t add data type i nformation . Th e c od e below is bas ed on s amples Q82 158 and Q1 42388 i n the Vi sual Bas ic Knowl edge Base. (See the "Bibl iograph y" sect ion for the fu ll referenc e.) Note For readabilit y on t he CD, we have added ret urns at the en d of lon g lines of code (for instanc e, t he "Private" li nes), whi ch wou ld not normal ly be t he c ase. T o make the code compile properl y, you will h ave to remove the retu rns. —Ed.

Option Explicit Private Declare Function GetProfileString Lib "Kernel" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Integer) As Integer Private Declare Function WriteProfileString Lib "Kernel" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any) As Integer Const BufferLen = 255 'Max Size of All INI Strings Public Property Get Value(AppName As String, KeyName As String) As String Dim Buffer As String * BufferLen, RC%, Default As String MsgBox AppName + KeyName + Buffer, BufferLen RC% = GetProfileString(AppName, KeyName, Default, Buffer, BufferLen) Value = Left$(Buffer, RC%) End Property Public Property Let Value(AppName As String, KeyName As String, vNewValue$) Dim RC% RC% = WriteProfileString(AppName, KeyName, vNewValue$) End Property

8 /1

1 1 / 4

0 0 2 s

Running the Server

The n ext s tage i s to make our project in to an execut able. This is d on e i n the usual way, b ut wh en you c omp ile it, your exec utable is als o regist ered as an OLE server automati cally. If you ru n it by press ing F5, the project is temp orari ly regist ered as an OLE server. If you open th e References di al og box in Mi cros oft E xc el or some other Vis ual Basi c for Applicat ions prod uct, you wi ll see the OLE server twi ce as s hown i n Fi gure 5. On e reference point s to the execu table and the other t o t he debu g version.

t n

e m e r i u q e R

http://msdn.microsoft.com/archive/en-us/dnarvb4/html/msdn_apiole.asp?frame=true

10/20/2007

Creating OLE Servers in Visual Basic to Simplify Windows Function Calls (Archived Vi...

Page 6 of 8

Figure 5. The References dialog box showing both compiled and debug OL E serv ers The extens ion on the file indi cates whether it i s the debuggi ng version (.VBP) or the compil ed version (.EXE or .DLL). When I need to debug my code, I select t he s erver with th e .VBP extensi on. For more informati on on deb ugging, see the document ation for Visual Basic 4 .0. Next I wi ll show you how I use this OLE s erver.

Using a WinAPI OLE Server from Microsoft Excel and from Microsoft Access 2.0 Vis ual Basi c 3.0 and Microsoft Ac cess 2.0 s upport on ly ordered arg uments for procedures , whil e l ater versi ons of these produc ts and all products incorporatin g Vis ual Bas ic for Applicat ions sup port both ordered argu men ts and named arguments. In this s ec tion I wil l illus trat e th e u se of my OLE server i n produc ts that s upport n amed arguments —specific al ly 32 -bit Microsoft Excel (version 5.0 or higher)—an d then illu strat e t he equ ivalent use in product s that su pport ordered argument s only (for example, 16 -bit Microsoft Ac cess, versi on 2.0 or lower.)

8 /1

Using an OLE Server from Visual Basic for Applications

Vis ual Basi c for Applicat ions is availabl e i n Vis ual Bas ic 4.0 or h igher, Mic rosoft Excel 5.0 or higher, Mi cros oft Projec t 4.0 or high er, and Microsoft Ac cess 95 or higher. Visu al Basic for Appl icati on s may be added to other p roduct s in fu ture vers ions, so thi s is the language to master for c orporat e developers or solu tion provi ders. After I have selected my OLE server in t he References d ialog box (see Figure 5 ), I press F2 to bring up the Ob ject Browser, whi ch I can us e t o p as te in the OLE server code. The c ode i s very simple, as shown below in a Microsoft Excel modu le sheet. "MyWin API" in t he dec larati on points t o t he p roject name I entered i nto the Opt ions dialog box in Fig ure 1. "WinINI" in the declaration poin ts to the Class Module name I entered into the module property sheet above in Figure 3.

1 1 / 4

0 0 2 s

Function WhereisMSINFO$() Dim WINini As New MyWinAPI.WinINI WhereisMSINFO$ = WINini.Value(AppName:="MSAPPS", KeyName:="msinfo") End Function

t n

I could di men sion the WINini variable either as Object or as MyWinAPI.WinINI. I always do th e lat ter by dec lari ng the MyWinAPI.WinINI t empl ate as New bec au se this results in early bind ing with very sign ificant performance improvement s. The Object u sed wit h CreateObject or GetObject result s in late bind ing and is considerably slower. See the OLE references in th e "Bibliography" s ection for further i nformation about early and late bindin g of OLE servers.

e m e r i u q e R

Using an OLE Server from Microsoft Access 2.0 or Lower Two problems are associ ated wit h using an OLE s erver in Mic rosoft Access 2 .0 or lower and in Visual Basic 3 .0 or lower: poor performanc e and th e abs en ce of named properties (and the ass oc iated Object Browser). The code must

http://msdn.microsoft.com/archive/en-us/dnarvb4/html/msdn_apiole.asp?frame=true

10/20/2007

Creating OLE Servers in Visual Basic to Simplify Windows Function Calls (Archived Vi...

Page 7 of 8

al ways us e Object and t hus does late bin ding. My c ode above becomes: Function WhereisMSINFO$ () Dim WINini As Object Set WINini = CreateObject("MyWinAPI.WinINI") WhereisMSINFO$ = WINini.Value("MSAPPS", "msinfo") End Function The c ode i s longer and i s more obtuse becaus e of the absenc e of named properties.

OLE Server or Visual Basic Class Module The c reation of OLE servers to handle all of your API call s cuts development t ime, s implifi es your code, and adds reusabil ity of compiled code across multi ple produc ts. If you are working s tric tly in 32 -bit mode, you may wish to create a version of the OLE server as an in -process s erver by compil ing it as a dynamic -link library (.DLL) instead of an execut ab le (.EXE). An in -process OLE s erver performs sign ificantl y fast er than an out -of -process s erver and al most as fast as an internal proc edure. If you are worki ng in the Visual Basic 4 .0 environment, you have another opt ion: You c ould inc lude the clas s modu les in your project inst ead of referring t o an OLE s erver. This result s in sl ightly better performanc e, bu t it loses many benefits avail able from an OLE server. The last q uestion is al ways, "What is t he performanc e penalt y?" If movin g API c al ls to procedures from i n -line code is acc ep table to you , u sing an in -process OLE s erver will be very ac ceptable —the percentage in crease is far l ess.

"Rolling Your Own" OLE Server That's it ! The simplic ity of this s ol ution and th e ease of implementati on seems an ticl imactic . An int erestin g as pect of this sol ution is that it has been availabl e for years — the undisc overed OLE server. I can now create addit ional properties and methods for my own server. Act ually, I would creat e three s erver projects th at use the same class modul es because there are di fferences between the API c alls in 1 6 -bit Windows and 32 -bit Windows (the regi stry func tions, for example). Als o, s ome API cal ls shoul d be don e as in -process OLE s erver calls —for example, GetCurrentProcess and GetPriorityClass . Th e best p erformance is al ways with an in -process OLE s erver with earl y bi nding (a 32 -bit DLL decl ared usin g t he New keyword). The i n-process OLE s erver will perform almost as fast as a cl ass module or a sub routi ne i n you r program. Table 1 summari zes my s uggested des ign.

1 1 / 4

Table 1. A group of WinAPI OLE Serv ers for Visual B asic for Applications Name (note extensions) APIOLE 16.EXE APIOLE 32.EXE APIOLE 32.DLL

OL E Serv er Type Out -of -process Out -of -process In -process (not acc essibl e from 16 -bit)

16-bit/32 -bit

8 /1

Server Name (see F igure 1) APIOLE 16 APIOLE 32 APIOLE 32P

0 0 2 s

16-bit 32-bit 32-bit

The ac tual clas ses you choose to implement are what you need to examin e n ext: Whic h API c alls go in to whi ch class an d whi ch server, and what names are you going t o g ive t o t hem? (Keep in mind t hat a b lind copyin g of th e SDK cannot be done for properties.) My journey in this artic le is finis hed; your journey has just st arted.

Bibliography

e m e r i u q e R

t n

Brockschmidt , Kraig. Insi de OLE 2 : The Fast Trac k to Build ing Powerful Object -Ori en ted Appl ication s wi th Windows Objects . Redmond, WA: Microsoft Press , 1994. (MSD N Library, Books) "How to Ap ply OLE 2 Tec hnologies i n Appl ication s." (MSDN Li brary Arch ive, Backgrou nders) Knowledge Bas e Q82158 . "How to Set Wi ndows Syst em Colors Using API and Vi sual Basic." (MSDN Library, Knowledge Bas e) Knowledge Bas e Q14238 8. "Changi ng WIN.INI Printer Settin gs from VB usi ng Windows API." (MSDN Li brary,

http://msdn.microsoft.com/archive/en-us/dnarvb4/html/msdn_apiole.asp?frame=true

10/20/2007

Creating OLE Servers in Visual Basic to Simplify Windows Function Calls (Archived Vi...

Page 8 of 8

Knowledge Bas e) Lasses en , Ken. "Corporate Developer's G uide to Offic e 95 API Issues ." (MSDN Li brary, Techn ical Arti cles, Appli cations ) Lasses en , Ken. "Iss ues to Cons ider When Porting 16 -bit Offic e Soluti ons to Windows 95." Developer Net work News 4 (May 1995). (MSDN Library, Periodic als, Microsoft Developer Network News) Lasses en , Ken. "Porting Your 16-Bit Office-Based Solution s to 32-Bit Office." (MSDN Li brary, Techn ical Arti cles, Appli cations ) "Mic rosoft OLE Today and Tomorrow: Technology Overview." (MSDN Library Archive, Bac kgrounders and White Papers, Operating Sys tem Extensions ) "Objec t Lin ki ng and Embedding 2 .0 Backgrounder." (MSDN Library Archive, Bac kg rounders and White Papers , Operati ng Syst em Extens ions)

Manage Your Profile | Legal | Contact Us | MSDN Flash New sletter © 2007 M icrosoft Corpora tion. All rights reserv ed. Terms of Use | Tra demark s | Priva cy Statem ent

8 /1

1 1 / 4

0 0 2 s

t n

e m e r i u q e R

http://msdn.microsoft.com/archive/en-us/dnarvb4/html/msdn_apiole.asp?frame=true

10/20/2007

Suggest Documents