Este artigo descreve como manipular eventos do Microsoft Office PowerPoint a partir de um cliente de automação que é desenvolvido usando o Microsoft Visual Basic .NET 2003.
Construir um manipulador de eventos
Você pode usar um dos seguintes métodos para construir um manipulador de eventos usando o Visual Basic. NET. O método que você escolher depende de como você deseja associar o manipulador de eventos com um evento.
Método 1
Normalmente, você cria um manipulador de eventos usando a palavra-chave Handles com a palavra-chave WithEvents . Quando declare uma variável de referência de objeto usando a palavra-chave WithEvents , Visual Basic .NET automaticamente conecta aos eventos do objeto em tempo de execução. Para manipular um evento específico para um objeto, adicione o manipulador relevante usando a classe listas de método do ambiente do Visual Studio .NET enquanto você estiver no código e exibir.
Método 2
Visual Basic .NET oferece outra maneira de manipular eventos. Você pode usar a instrução AddHandler e a instrução RemoveHandler para que você pode dinamicamente iniciar e interromper dinamicamente tratamento de evento para um evento específico.
Observação Se você utilizar a palavra-chave WithEvents para construir os manipuladores de eventos, você poderá receber uma exceção System.Reflection.TargetInvocationException . Portanto, use o evento AddHandler para construir os manipuladores de eventos.
Criar o cliente de automação do Visual Basic .NET que manipula eventos do PowerPoint
Os conjuntos de etapas a seguir mostram como usar a instrução AddHandler para manipular os eventos do aplicativo PowerPoint a partir de um cliente de automação que é desenvolvido usando o Visual Basic. NET.
Para criar um projeto Visual Basic.NET, execute essas etapas:
Iniciar Microsoft Visual Studio .NET 2003.
No menu arquivo , clique em novo e, em seguida, clique em Project .
Na lista Tipos de projeto , clique em Projetos do Visual Basic . Na lista Templates , clique em Windows Application .
Nome do projeto PowerPointEvents e, em seguida, clique em OK .
Por padrão, um formulário que é denominado Form1 é criado.
Para adicionar referências a biblioteca de objetos do Microsoft PowerPoint e a biblioteca de objetos de gráfico do Microsoft, siga estas etapas:
No menu Project , clique em Add Reference .
Na guia COM , clique em uma das seguintes opções e, em seguida, clique em Selecionar :
Para Microsoft Office PowerPoint 2007, clique em Microsoft PowerPoint 12.0 Object Library .
Para Microsoft Office PowerPoint 2003, clique em Microsoft PowerPoint 11.0 Object Library .
Na guia COM , clique em uma das seguintes opções e, em seguida, clique em Selecionar :
Para o Microsoft Graph 12.0, clique em Microsoft Graph 12.0 Object Library .
Para o Microsoft Graph 11.0, clique em Microsoft Graph 11.0 Object Library .
Na caixa de diálogo Add References , clique em OK para aceitar as seleções.
Clique duas vezes no formulário.
A janela de código é aberta.
Na parte superior do arquivo Form1.vb, adicione o seguinte código:
No menu Exibir , clique em caixa de ferramentas e, em seguida, adicione um botão ao Form1.
Clique duas vezes em Button1 .
A janela de código abrirá no evento Button1_Click .
Na janela código, coloque o seguinte código antes do evento Button1_Click :
Dim oApp As PowerPoint.Application
Dim oPres As PowerPoint.Presentation
Adicione o seguinte código ao evento Button1_Click :
Const sTemplate = "C:\Program Files\Microsoft Office\Templates\Presentation Designs\Orbit.pot"
' If the previous template is not available, change the template name to a template name that is on your system.
Const sVideo = "C:\WINDOWS\system32\oobe\images\intro.wmv"
Dim oPresentations As PowerPoint.Presentations
Dim oSlides As PowerPoint.Slides
Dim oSlide As PowerPoint.Slide
Dim oShapes As PowerPoint.Shapes
Dim oShape As PowerPoint.Shape
Dim oMovie As PowerPoint.Shape
Dim oAnimationSettings As PowerPoint.AnimationSettings
Dim oPlaySettings As PowerPoint.PlaySettings
Dim oTextFrame As PowerPoint.TextFrame
Dim oTextRange As PowerPoint.TextRange
Dim oFont As PowerPoint.Font
Dim oOLEFormat As PowerPoint.OLEFormat
Dim oShadow As PowerPoint.ShadowFormat
Dim oForeColor As PowerPoint.ColorFormat
Dim oRange As PowerPoint.SlideRange
Dim oSlideShowTransition As PowerPoint.SlideShowTransition
'Start PowerPoint and then make the PowerPoint window visible but minimized.
oApp = New PowerPoint.Application
'Add event handlers.
AddHandler oApp.SlideShowBegin, AddressOf oApp_SlideShowBegin
AddHandler oApp.SlideShowNextSlide, AddressOf oApp_SlideShowNextSlide
AddHandler oApp.PresentationClose, AddressOf oApp_PresentationClose
oApp.Visible = True
oApp.WindowState = PowerPoint.PpWindowState.ppWindowMinimized
'Create a new presentation that is based on the specified template.
oPresentations = oApp.Presentations
oPres = oPresentations.Open(sTemplate, , , True)
'Build slide 1.
'Add text to the slide, change the font, and then insert or position a
'movie on the first slide.
oSlides = oPres.Slides
oSlide = oSlides.Add(1, PowerPoint.PpSlideLayout.ppLayoutTitleOnly)
oShapes = oSlide.Shapes
oShape = oShapes.Item(1)
oTextFrame = oShape.TextFrame
oTextRange = oTextFrame.TextRange
oTextRange.Text = "My sample presentation"
oFont = oTextRange.Font
oFont.Name = "Comic Sans MS"
oFont.Size = 48
oMovie = oShapes.AddMediaObject(sVideo, 150, 150, 500, 350)
oAnimationSettings = oMovie.AnimationSettings
oPlaySettings = oAnimationSettings.PlaySettings
oPlaySettings.PlayOnEntry = True
oPlaySettings.HideWhileNotPlaying = True
'NAR to release references.
NAR(oPlaySettings)
NAR(oAnimationSettings)
NAR(oMovie)
NAR(oFont)
NAR(oTextRange)
NAR(oTextFrame)
NAR(oShape)
NAR(oShapes)
NAR(oSlide)
NAR(oSlides)
'Build slide 2.
'Add text to the slide title and then format the text. Also, add a chart to the
'slide and then change the chart type to a 3D Column Clustered.
oSlides = oPres.Slides
oSlide = oSlides.Add(2, PowerPoint.PpSlideLayout.ppLayoutTitleOnly)
oShapes = oSlide.Shapes
oShape = oShapes.Item(1)
oTextFrame = oShape.TextFrame
oTextRange = oTextFrame.TextRange
oTextRange.Text = "My chart"
oFont = oTextRange.Font
oFont.Name = "Comic Sans MS"
oFont.Size = 48
Dim oChart As Graph.Chart
oShape = oShapes.AddOLEObject(150, 150, 480, 320, "MSGraph.Chart.8")
oOLEFormat = oShape.OLEFormat
oChart = oOLEFormat.Object
oChart.ChartType = Graph.XlChartType.xl3DColumnClustered
'NAR to release references.
NAR(oChart)
NAR(oOLEFormat)
NAR(oFont)
NAR(oTextRange)
NAR(oTextFrame)
NAR(oShape)
NAR(oShapes)
NAR(oSlide)
NAR(oSlides)
'Build slide 3.
'Add a text effect to the slide and then apply shadows to the text effect.
oSlides = oPres.Slides
oSlide = oSlides.Add(3, PowerPoint.PpSlideLayout.ppLayoutBlank)
oSlide.FollowMasterBackground = False
oShapes = oSlide.Shapes
oShape = oShapes.AddTextEffect(Office.MsoPresetTextEffect.msoTextEffect27, _
"The End", "Impact", 96, False, False, 230, 200)
oShadow = oShape.Shadow
oForeColor = oShadow.ForeColor
oForeColor.SchemeColor = PowerPoint.PpColorSchemeIndex.ppForeground
oShadow.Visible = True
oShadow.OffsetX = 3
oShadow.OffsetY = 3
'NAR to release references.
NAR(oShadow)
NAR(oForeColor)
NAR(oShape)
NAR(oShapes)
NAR(oSlide)
NAR(oSlides)
'Modify the slide show transition settings for all three slides in
'the presentation.
Dim SlideIdx(3) As Integer
SlideIdx(0) = 1
SlideIdx(1) = 2
SlideIdx(2) = 3
oSlides = oPres.Slides
oRange = oSlides.Range(SlideIdx)
oSlideShowTransition = oRange.SlideShowTransition
oSlideShowTransition.AdvanceOnTime = False
oSlideShowTransition.EntryEffect = PowerPoint.PpEntryEffect.ppEffectBoxOut
'Run the slide show in a separate method.
RunSlideShow()
'NAR to release references.
NAR(oSlideShowTransition)
NAR(oRange)
NAR(oSlides)
'Close the presentation without saving changes and then quit PowerPoint.
oPres.Saved = True
oPres.Close()
'NAR the presentation objects.
NAR(oPres)
NAR(oPresentations)
'Remove all event handlers.
RemoveHandler oApp.SlideShowBegin, AddressOf oApp_SlideShowBegin
RemoveHandler oApp.SlideShowNextSlide, AddressOf oApp_SlideShowNextSlide
RemoveHandler oApp.PresentationClose, AddressOf oApp_PresentationClose
'Quit PowerPoint.
oApp.Quit()
NAR(oApp)
GC.Collect()
Na janela código, coloque o seguinte código abaixo o evento Button1_Click :
Private Sub RunSlideShow()
Dim oSettings As PowerPoint.SlideShowSettings
Dim oSlideShowWindows As PowerPoint.SlideShowWindows
oSettings = oPres.SlideShowSettings
oSettings.StartingSlide = 1
oSettings.EndingSlide = 3
'Run the slide show. Wait for the slide show to finish.
oSettings.Run()
oSlideShowWindows = oApp.SlideShowWindows
On Error Resume Next
Do While oSlideShowWindows.Count >= 1
System.Windows.Forms.Application.DoEvents()
Loop
NAR(oSlideShowWindows)
NAR(oSettings)
End Sub
'NAR function to remove reference.
Private Sub NAR(ByVal o As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
Catch
Finally
o = Nothing
End Try
End Sub
Adicionar manipuladores de evento abaixo do código anterior:
'Event Handlers
Private Sub oApp_SlideShowBegin(ByVal Wn As Microsoft.Office.Interop.PowerPoint.SlideShowWindow)
'Change the position and the size of the slide show window.
Dim oView As PowerPoint.SlideShowView
With Wn
.Height = 325
.Width = 400
.Left = 100
.Activate()
End With
'Start the movie at the first slide.
oView = Wn.View
oView.Next()
NAR(oView)
NAR(Wn)
End Sub
Private Sub oApp_SlideShowNextSlide(ByVal Wn As Microsoft.Office.Interop.PowerPoint.SlideShowWindow)
'Change the color and the type of pointer depending on the slide.
Dim Showpos As Integer
Dim oView As PowerPoint.SlideShowView
Dim oColorFormat As PowerPoint.ColorFormat
oView = Wn.View
Showpos = oView.CurrentShowPosition + 1
If Showpos = 3 Then
oColorFormat = oView.PointerColor
oColorFormat.RGB = RGB(255, 0, 0)
oView.PointerType = PowerPoint.PpSlideShowPointerType.ppSlideShowPointerPen
Else
oColorFormat = oView.PointerColor
oColorFormat.RGB = RGB(0, 0, 0)
oView.PointerType = PowerPoint.PpSlideShowPointerType.ppSlideShowPointerArrow
End If
NAR(oColorFormat)
NAR(oView)
NAR(Wn)
End Sub
Private Sub oApp_PresentationClose(ByVal Pres As Microsoft.Office.Interop.PowerPoint.Presentation)
'Before you close the presentation, save the presentation as HTML.
Pres.SaveAs("C:\TestEvents.htm", PowerPoint.PpSaveAsFileType.ppSaveAsHTML)
NAR(Pres)
End Sub
Experimente
Pressione F5 para executar o aplicativo.
Clique em Button1 .
PowerPoint for iniciado a apresentação de slides. Observe o seguinte:
O primeiro slide inicia um filme.
O tipo de ponteiro.
A cor é alterada do segundo slide que contém um gráfico.
Como usar a automação para criar e para mostrar uma apresentação do PowerPoint 2002 ou uma apresentação do Office PowerPoint 2003 usando Visual Basic .NET 2002 ou Visual Basic .NET 2003
IMPORTANTE: Este artigo foi traduzido por um sistema de tradução automática (também designado por Machine Translation ou MT), não tendo sido portanto traduzido ou revisto por pessoas. A Microsoft possui artigos traduzidos por aplicações (MT) e artigos traduzidos por tradutores profissionais, com o objetivo de oferecer em português a totalidade dos artigos existentes na base de dados de suporte. No entanto, a tradução automática não é sempre perfeita, podendo conter erros de vocabulário, sintaxe ou gramática. A Microsoft não é responsável por incoerências, erros ou prejuízos ocorridos em decorrência da utilização dos artigos MT por parte dos nossos clientes. A Microsoft realiza atualizações freqüentes ao software de tradução automática (MT). Obrigado.
Clique aqui para ver a versão em Inglês deste artigo: 824021
Obrigado! Seus comentários são usados para nos ajudar a aperfeiçoar o conteúdo de suporte. Para obter mais opções de ajuda, visite a Home Page de Ajuda e Suporte.