Help and Support

Numéro d'article: 274326 - Dernière mise à jour: jeudi 24 mai 2007 - Version: 5.1

Comment ajouter code HTML dans le Presse-papiers à l'aide de Visual Basic

Sommaire

Agrandir tout | Réduire tout

Résumé

Cet article explique comment ajouter et de récupérer les données HTML dans le Presse-papiers Microsoft Windows en utilisant Visual Basic.

Plus d'informations

Les développeurs peuvent utiliser le format de presse-papiers CF_HTML (format HTML) pour partager des données HTML avec d'autres applications qui comprennent le HTML, tels que Microsoft Office et Microsoft Internet Explorer.

CF_HTML est entièrement un format basé sur du texte qui inclut une description, un contexte et un fragment dans ce contexte. Lorsque vous créez des données à envoyer dans le Presse-papiers, vous devez inclure une description des données pour indiquer la version du Presse-papiers et les décalages du contexte et fragment. Vous pouvez utiliser la procédure PutHTMLClipboard décrite plus loin dans cet article pour simplifier cette tâche.

Étapes pour créer un exemple de projet

  1. Démarrer un nouveau projet EXE standard dans Visual Basic. Form1 est créé par défaut.
  2. Ajoutez deux contrôles CommandButton à Form1. Modifier la propriété Caption de Command1 à placer le HTML et modifier la propriété Caption du Command2 au format HTML obtenir .
  3. Dans le menu projet , choisissez Ajouter un module pour ajouter un module standard BAS le projet.
  4. Ajoutez le code suivant à la fenêtre de module :
    
    Option Explicit
    
    Private Declare Function CloseClipboard Lib "user32" () As Long
    Private Declare Function OpenClipboard Lib "user32" (ByVal hWnd As Long) _
       As Long
    Private Declare Function GlobalAlloc Lib "kernel32" ( _
    
       ByVal wFlags As Long, ByVal dwBytes As Long) As Long
    Private Declare Function SetClipboardData Lib "user32" ( _
       ByVal wFormat As Long, ByVal hMem As Long) As Long
    Private Declare Function EmptyClipboard Lib "user32" () As Long
    Private Declare Function RegisterClipboardFormat Lib "user32" Alias _
       "RegisterClipboardFormatA" (ByVal lpString As String) As Long
    Private Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) _
       As Long
    Private Declare Function GlobalUnlock Lib "kernel32" ( _
       ByVal hMem As Long) As Long
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
       pDest As Any, pSource As Any, ByVal cbLength As Long)
    Private Declare Function GetClipboardData Lib "user32" ( _
       ByVal wFormat As Long) As Long
    Private Declare Function lstrlen Lib "kernel32" Alias "lstrlenA" ( _
       ByVal lpData As Long) As Long
    
    Private Const m_sDescription = _
                      "Version:1.0" & vbCrLf & _
                      "StartHTML:aaaaaaaaaa" & vbCrLf & _
                      "EndHTML:bbbbbbbbbb" & vbCrLf & _
                      "StartFragment:cccccccccc" & vbCrLf & _
                      "EndFragment:dddddddddd" & vbCrLf
                      
    Private m_cfHTMLClipFormat As Long
    
    Function RegisterCF() As Long
    
    
       'Register the HTML clipboard format
       If (m_cfHTMLClipFormat = 0) Then
          m_cfHTMLClipFormat = RegisterClipboardFormat("HTML Format")
       End If
       RegisterCF = m_cfHTMLClipFormat
       
    End Function
    
    Public Sub PutHTMLClipboard(sHtmlFragment As String, _
       Optional sContextStart As String = "<HTML><BODY>", _
       Optional sContextEnd As String = "</BODY></HTML>")
       
       Dim sData As String
       
       If RegisterCF = 0 Then Exit Sub
       
       'Add the starting and ending tags for the HTML fragment
       sContextStart = sContextStart & "<!--StartFragment -->"
       sContextEnd = "<!--EndFragment -->" & sContextEnd
       
       'Build the HTML given the description, the fragment and the context.
       'And, replace the offset place holders in the description with values
       'for the offsets of StartHMTL, EndHTML, StartFragment and EndFragment.
       sData = m_sDescription & sContextStart & sHtmlFragment & sContextEnd
       sData = Replace(sData, "aaaaaaaaaa", _
                       Format(Len(m_sDescription), "0000000000"))
       sData = Replace(sData, "bbbbbbbbbb", Format(Len(sData), "0000000000"))
       sData = Replace(sData, "cccccccccc", Format(Len(m_sDescription & _
                       sContextStart), "0000000000"))
       sData = Replace(sData, "dddddddddd", Format(Len(m_sDescription & _
                       sContextStart & sHtmlFragment), "0000000000"))
    
       'Add the HTML code to the clipboard
       If CBool(OpenClipboard(0)) Then
       
          Dim hMemHandle As Long, lpData As Long
          
          hMemHandle = GlobalAlloc(0, Len(sData) + 10)
          
          If CBool(hMemHandle) Then
                   
             lpData = GlobalLock(hMemHandle)
             If lpData <> 0 Then
                
                CopyMemory ByVal lpData, ByVal sData, Len(sData)
                GlobalUnlock hMemHandle
                EmptyClipboard
                SetClipboardData m_cfHTMLClipFormat, hMemHandle
                            
             End If
          
          End If
       
          Call CloseClipboard
       End If
    
    End Sub
    
    Public Function GetHTMLClipboard() As String
    
       Dim sData As String
       
       If RegisterCF = 0 Then Exit Function
       
       If CBool(OpenClipboard(0)) Then
       
          Dim hMemHandle As Long, lpData As Long
          Dim nClipSize As Long
          
          GlobalUnlock hMemHandle
    
          'Retrieve the data from the clipboard
          hMemHandle = GetClipboardData(m_cfHTMLClipFormat)
          
          If CBool(hMemHandle) Then
                   
             lpData = GlobalLock(hMemHandle)
             If lpData <> 0 Then
                nClipSize = lstrlen(lpData)
                sData = String(nClipSize + 10, 0)
                
    
                Call CopyMemory(ByVal sData, ByVal lpData, nClipSize)
                
                Dim nStartFrag As Long, nEndFrag As Long
                Dim nIndx As Long
                
                'If StartFragment appears in the data's description,
                'then retrieve the offset specified in the description
                'for the start of the fragment. Likewise, if EndFragment
                'appears in the description, then retrieve the
                'corresponding offset.
                nIndx = InStr(sData, "StartFragment:")
                If nIndx Then
                   nStartFrag = CLng(Mid(sData, _
                                     nIndx + Len("StartFragment:"), 10))
    
                End If
                nIndx = InStr(sData, "EndFragment:")
                If nIndx Then
                   nEndFrag = CLng(Mid(sData, nIndx + Len("EndFragment:"), 10))
                End If
                
                'Return the fragment given the starting and ending
                'offsets
                If (nStartFrag > 0 And nEndFrag > 0) Then
                   GetHTMLClipboard = Mid(sData, nStartFrag + 1, _
                                     (nEndFrag - nStartFrag))
                End If
                            
             End If
          
          End If
    
       
          Call CloseClipboard
       End If
    
    
    End Function
    					
  5. Ajoutez le code suivant dans la fenêtre de code pour Form1 :
    Private Sub Command1_Click()
        Dim sFrag As String, sStart As String, sEnd As String
        sStart = "<HTML><BODY><FONT FACE=Arial SIZE=1 COLOR=BLUE>"
        sFrag = "<B>This is bold</B> and <I>this is italic.</I>"
        sEnd = "</FONT></BODY></HTML>"
        PutHTMLClipboard sFrag, sStart, sEnd
    End Sub
    
    Private Sub Command2_Click()
        MsgBox GetHTMLClipboard
    End Sub
    					
  6. Appuyez sur la touche F5 pour démarrer le programme Visual Basic. Cliquez sur Insertion HTML pour ajouter les données HTML dans le Presse-papiers. Ensuite, cliquez sur HTML extraire pour extraire les données du Presse-papiers. Notez qu'une boîte de message affiche le fragment HTML.
  7. Démarrez Microsoft Word (ou toute application qui reconnaît le format HTML pour le Presse-papiers). Coller le contenu du Presse-papiers dans un nouveau document pour examiner les résultats du code HTML contenu dans le Presse-papiers.

Notes supplémentaires

Une approche qui envoie le code HTML vers le Presse-papiers peut être particulièrement utile pour les clients Office Automation. Par exemple, si vous avez un client Automation à générer des données pour les cellules mises en forme dans Microsoft Excel ou des paragraphes dans Microsoft Word, vous pourriez créer les données de code HTML, envoyez-le au Presse-papiers et puis collez-le dans l'application. En utilisant cette technique, vous pouvez réduire le nombre d'appels out-of-process vers le client Automation.

Références

Pour en savoir plus sur les spécificités du format de presse-papiers HTML, consultez la rubrique « Format de Presse-papiers HTML » sur le site Web MSDN (Microsoft Developer Network) suivant :
http://msdn2.microsoft.com/en-us/library/Aa767917.aspx (http://msdn2.microsoft.com/en-us/library/Aa767917.aspx)

Les informations contenues dans cet article s'appliquent au(x) produit(s) suivant(s):
  • Microsoft Visual Basic 6.0 Édition professionnelle
  • Microsoft Visual Basic 5.0 Édition professionnelle
  • Microsoft Visual Basic Enterprise Edition for Windows 6.0
  • Microsoft Visual Basic 5.0 Édition Entreprise
  • Microsoft Office Basic 2007
  • Microsoft Office Enterprise 2007
  • Microsoft Office Home and Student 2007
  • Microsoft Office Professional 2007
  • Microsoft Office Professional Plus 2007
  • Microsoft Office PME 2007
  • Microsoft Office Standard 2007
  • Microsoft Office Ultimate 2007
  • Microsoft Office Édition Professionnelle 2003
  • Microsoft Office Édition Basique 2003
  • Microsoft Office Édition PME 2003
  • Microsoft Office XP Developer
  • Microsoft Office 2000 Developer
Mots-clés : 
kbmt kbexpertiseinter kbclipboard kbhowto kbhtml KB274326 KbMtfr
Traduction automatiqueTraduction automatique
IMPORTANT : Cet article est issu du système de traduction automatique mis au point par Microsoft (http://support.microsoft.com/gp/mtdetails). Un certain nombre d?articles obtenus par traduction automatique sont en effet mis à votre disposition en complément des articles traduits en langue française par des traducteurs professionnels. Cela vous permet d?avoir accès, dans votre propre langue, à l?ensemble des articles de la base de connaissances rédigés originellement en langue anglaise. Les articles traduits automatiquement ne sont pas toujours parfaits et peuvent comporter des erreurs de vocabulaire, de syntaxe ou de grammaire (probablement semblables aux erreurs que ferait une personne étrangère s?exprimant dans votre langue !). Néanmoins, mis à part ces imperfections, ces articles devraient suffire à vous orienter et à vous aider à résoudre votre problème. Microsoft s?efforce aussi continuellement de faire évoluer son système de traduction automatique.
La version anglaise de cet article est la suivante: 274326  (http://support.microsoft.com/kb/274326/en-us/ )
L'INFORMATION CONTENUE DANS CE DOCUMENT EST FOURNIE PAR MICROSOFT SANS GARANTIE D'AUCUNE SORTE, EXPLICITE OU IMPLICITE. L'UTILISATEUR ASSUME LE RISQUE DE L'UTILISATION DU CONTENU DE CE DOCUMENT. CE DOCUMENT NE PEUT ETRE REVENDU OU CEDE EN ECHANGE D'UN QUELCONQUE PROFIT.

Traductions disponibles