Forum des développeurs  

Le forum de référence en programmation et développement. Articles, cours et tutoriels du débutant au chef de projet et DBA confirmé.
Précédent   Forum des développeurs > Autres langages > Autres langages > Basic > PureBasic

Réponse
 
Outils de la discussion
Vieux 06/09/2008, 17h50   #1 (permalink)
Responsable Purebasic
 
Date d'inscription: avril 2003
Messages: 334
Par défaut COMate - Contrôle des objets COM

Mon anglais étant plus que douteux et limité, un coup de pouce pour traduire ce texte serait le bienvenue.

Téléchargez COMate sur ce site : http://www.nxsoftware.com/

L'auteur s'est basé sur le code open source DispHelper écrit en C, qu'il a converti en PureBasic. L'archive contient un fichier d'aide,les sources en PureBasic et le code source d'une vingtaine d'exemples (utilisation des OCX , ouverture d'une feuille excel et remplissage des cellules, etc ...)

Pour vous mettre en appétit, voici un des exemples (il ouvre une feuille excel et écrit dans les cellules)

Code :
;/////////////////////////////////////////////////////////////////////////////////
;***COMate***  COM automation through iDispatch.
;*===========
;*
;*Excel demo.
;/////////////////////////////////////////////////////////////////////////////////
 
IncludePath "..\"
XIncludeFile "COMate.pbi"
 
 
date$ = FormatDate("%dd/%mm/%yyyy", Date())
 
Define.COMateObject ExcelObject, WorkBook
ExcelObject = COMate_CreateObject("Excel.Application")
 
If ExcelObject
  If ExcelObject\SetProperty("Visible = #True") = #S_OK
    WorkBook = ExcelObject\GetObjectProperty("Workbooks\Add")
    If WorkBook
      ExcelObject\SetProperty("Cells(1,1) = 'Hello'")
      ExcelObject\SetProperty("Cells(1,2) = 'from'")
      ExcelObject\SetProperty("Cells(1,3) = 'COMate!'")
      ExcelObject\SetProperty("Cells(1,5) = 'Today$0027s date is'")  ;$0027 is a hex escape code used to insert a ' (ascii 39) character.
      ExcelObject\SetProperty("Cells(1,6) = '" + date$ + "' AS DATE")
      ExcelObject\SetProperty("Cells(4,1) = 6.25")
      ;Retrieve a double value and a date.
        dbl.d = ExcelObject\GetRealProperty("Cells(4,1)")
          MessageRequester("COMate - Excel demo", "Result Cells(4,1) : " + StrD(dbl))
      ;For the date we retrieve it in string format.
        newDate$ = ExcelObject\GetStringProperty("Cells(1,6)")
          MessageRequester("COMate - Excel demo", "Result Cells(1,6) : " + newDate$)
      ExcelObject\Invoke("Quit()") 
      WorkBook\Release()
    EndIf
  EndIf
  ExcelObject\Release()
Else
  MessageRequester("COMate -Excel demo", "Couldn't create the application object!")
EndIf
Citation:
Hi,

in association with ts-soft enterprises Wink I bring you COMate, a PB utility for controlling COM automation servers (components).

Realising that a couple of projects I am working on will soon require to use some COM I decided to study OLE automation in depth, and the best way I found of doing this was to grab the open-source DispHelper library (written in c) and convert it to Purebasic. I have of course modified the library to suit my own ends!

The main thing is that whilst the original DispHelper library uses a c-style Printf() syntax, my offering (COMate) uses what is, for me at least, a much more comfortable Visual Basic like syntax.

Contrast :

VB code :

Code :
Dim excel As Object
Set excel = CreateObject("Excel.Application")
excel.Visible = blnTrue

converted to Purebasic with the PureDispHelper library :

Code :
Define.l ExcelApp
ExcelApp = dhCreateObject("Excel.Application")
dhPutValue(ExcelApp, ".Visible = %b", #True)

and now converted to Purebasic with COMate :

Code :
ExcelObject.COMateObject
ExcelObject = COMate_CreateObject("Excel.Application")
ExcelObject\SetProperty("Visible = #True")
Features of COMate :

* Completely free!
* It comes in the form of a PB source code include file.
* Ansi or Unicode and/or Threadsafe etc. (Well, as threadsafe as any COM components you may be controlling!)
* An oop interface.
* Method / property parameters are encoded in a very natural (VB) way within command strings.
* Method/property calls can embed a chain of property-gets, each of which return a subobject etc. (all handled automatically by COMate).
* Command strings can include escape characters in the form $xxxx where xxxx represents a 4 hexadecimal digit character code.
* Easy enumeration of collections.
* Automatic freeing of all strings (unlike DispHelper).
* Full threaded error reporting. Each thread can report (if requested) the most recent COM error as well as a 'friendly' text description if appropriate. This means that if two threads are, for example, working on the same instance of a COM component, then the errors reported in one thread will not affect the other thread!



I think you'd get a good feel for COMate (as well as the differences between this and DispHelper) by browsing the various demo programs which are mostly simple conversions of the PureDispHelper demo programs written by ts-soft, mk-soft and Kiffi; to whom I offer my thanks.

COMate itself uses some code developed by ts-soft and he has been instrumental in helping me test COMate and indeed he translated some of the demo programs for use with COMate. ts-soft is thus very much a part of this project. Indeed, I would like to state right now that he is to be held responsible for any bugs!

The COMate package includes the two source include files (one just has constants etc.) various demos and a very comprehensive CHM user manual. This manual is really the first place for those who have never used COM before.

You can access the download through the nxSoftware site.

============================================
Update - version 1.1.0. 6th Sept. 2008.
My thanks to all those who have tested out the first version of COMate and to SFSxOI in particular for creating some nice WMI demos.

Changes for this new version include :

* Addition of a 'BYREF' parameter type-modifier. This is for calling methods (VB) in which certain parameters have been declared with the 'ByRef' modifier. For many COM objects it is not enough to simply pass the address of a variable, you will also need to use this new modifier. Particularly true for components created in VB.

* COMate can now house ActiveX controls. See the demo programs and the help manual for details. I haven't added 'Event sinks' yet for trapping events/messages sent by such controls, but it is only a matter of time! Wink Consider this part to be in 'beta' stage because I took a slightly different approach here than PureDispHelper and so it remains to be seen whether more than just a handful of ActiveX controls will function correctly?

* Have totally rewritten the command parser and various utility functions in order to increase the speed. DispHelper does not utilise such a parser and so will of course generally run faster. Increasing the speed has been accomplished by simply removing all PB string functions from the aforementioned functions and replacing with memory buffers and 'in place' alteration (via pointers) of strings. Tests on my machine of these functions (when stripped from COMate) show a x50 increase in speed. Take this with a pinch of salt though! It remains to be seen what effect (if any) these new routines will have, speed-wise, on COMate itself.
This new version is now to be known as COMate-Turbo!

* Have included a slightly modified version of mk-soft's / ts-soft's excellent 'VariantHelper' utility within the COMate-Turbo download, because there was a slight bug with the 'SafeArray' macros. Some COM methods/properties will return a SafeArray (yuk!) See the 'Demo_IPAddresses.pb' demo for an example of dealing with a return from a COM method in the form of a SafeArray.
NOTE that the VariantHelper utility can only deal with SafeArray's of one dimension. Beyond this you are on your own!


See the nxSoftware site for the download.

=========================================
__________________
Rubrique PureBasic
comtois est déconnecté   Envoyer un message privé Réponse avec citation
Vieux 07/09/2008, 18h32   #2 (permalink)
Responsable Purebasic
 
Date d'inscription: avril 2003
Messages: 334
Par défaut

Nouvelle mise à jour disponible

Citation:
Update - version 1.1.1. 7th Sept. 2008.
Apart from fixing the whole BYREF business which was completely flawed and ill thought out, I have plugged a major hole in COMate's supported parameter types, namely variants! Doh! Needless to say you can now pass variants by value or by reference (See Num3's Open Office example which is posted in this thread!)

There are a couple of things to beware of with COMate parameters (and in particular when using BYREF) which I leave to the help manual (see the page on 'COMate command strings' for details).

Finally, for those enaged with (or to ) WMI, there is a very very useful scripting utility which I came across which I have thrown into the COMate package and which should make things a lot easier!

See the nxSoftware site for the download.

Right, I'm off to study 'Event sinks' now... Let's hope I have more luck than I generally do with kitchen sinks!
Et voici les exemples de Num3 mentionnés ci dessus :

Code x :
;works with OpenOffice 2/3 and also with IBM Symphony (aka Open Office with less bugs) 
XIncludeFile "COMate.pbi"
XIncludeFile "VariantHelper_Include.pb"


Procedure.s ConvertToUrl(strFile.s)
strFile = ReplaceString(strFile, "\", "/")
strFile = ReplaceString(strFile, ":", "|")
strFile = ReplaceString(strFile, " ", "%20")
strFile = "file:///" + strFile
ProcedureReturn strFile
EndProcedure


Define.COMateObject oSM, oDesk, oDoc

Define.safearray *openpar
Define.variant openarray

V_ARRAY_DISP(openarray) = safearray

oSM = COMate_CreateObject("com.sun.star.ServiceManager")
If oSM
  ;Creating instance of Desktop
    oDesk = oSM\GetObjectProperty("CreateInstance('com.sun.star.frame.Desktop')")
    If oDesk
      ;Opening a exisiting Document
        document.s = GetCurrentDirectory() + "test.odt"       
        oDoc = oDesk\GetObjectProperty("loadComponentFromURL('"+ConvertToUrl(document)+"', '_blank', 0, " + Str(openarray) + " as variant)")
       
        Debug COMate_GetLastErrorDescription()
       
      If oDoc
        oDoc\Release()
      EndIf
      oDesk\Release()   
    EndIf
  oSM\Release()
EndIf

Exemple pour ouvrir un document vide

Code x :
XIncludeFile "COMate.pbi"
XIncludeFile "VariantHelper_Include.pb"


Procedure.s ConvertToUrl(strFile.s)
strFile = ReplaceString(strFile, "\", "/")
strFile = ReplaceString(strFile, ":", "|")
strFile = ReplaceString(strFile, " ", "%20")
strFile = "file:///" + strFile
ProcedureReturn strFile
EndProcedure


Define.COMateObject oSM, oDesk, oDoc

Define.safearray *openpar
Define.variant openarray

V_ARRAY_DISP(openarray) = safearray

oSM = COMate_CreateObject("com.sun.star.ServiceManager")
If oSM
  ;Creating instance of Desktop
    oDesk = oSM\GetObjectProperty("CreateInstance('com.sun.star.frame.Desktop')")
    If oDesk
      ;Opening a new writer Document   
        oDoc = oDesk\GetObjectProperty("loadComponentFromURL('private:factory/swriter', '_blank', 0, " + Str(openarray) + " as variant)")     
      If oDoc
        oDoc\Release()
      EndIf
      oDesk\Release()   
    EndIf
  oSM\Release()
EndIf
__________________
Rubrique PureBasic

Dernière modification par comtois ; 07/09/2008 à 18h34 Motif: suppression colorisation code (elle ne correspond pas à PureBasic)
comtois est déconnecté   Envoyer un message privé Réponse avec citation
NEWS PUREBASICFAQ PureBasicTutoriels PureBasicSources PureBasic

Réponse

Précédent   Forum des développeurs > Autres langages > Autres langages > Basic > PureBasic



Outils de la discussion

Règles de messages
Vous ne pouvez pas créer de nouvelles discussions
Vous ne pouvez pas envoyer des réponses
Vous ne pouvez pas envoyer des pièces jointes
Vous ne pouvez pas modifier vos messages

Les balises BB sont activées : oui
Les smileys sont activés : oui
La balise [IMG] est activée : oui
Le code HTML peut être employé : non
Trackbacks are non
Pingbacks are non
Refbacks are non
Navigation rapide