ActiveX - Jurandir A Pellin 1
&
ActiveX - Jurandir A Pellin 2
Tecnologia e Aplicações ActiveX é um conjunto de tecnologias desenvolvidas pela Microsoft em meados da década de 1990
no sentido de facilitar a criação de "Web sites" interativos e um rápido desenvolvimento de
controles especiais para a Internet.
A tecnologia ActiveX esta revolucionando a Web. Através de controles ActiveX, pode-se construir
verdadeiras aplicações nas paginas Web, multiplicando a potencialidade de sites Internet e intranet.
O VBScript, uma linguagem script da família do Visual Basic, permite uma poderosa interação
entre os controles ActiveX e o Internet Explorer, através do acesso direto a estrutura de objetos do
browser. Alem disso, oferece ao desenvolvedor Web a possibilidade de critica de informações no
cliente, atualização dinâmica de frames, etc. Com a ferramenta de autoria ActiveX Control Pad, em
segundos podem ser inseridos novos objetos (controles) nas paginas HTML. Ela também permite a
criação 'WYSIWYG' de scripts VBS e JavaScript.
Um ActiveX Document é um programa que roda num browser, tendo até seus menus incorporados.
Eles podem ser gerados a partir do VB5, Delphi e VC++. As zonas de segurança acabaram com o
problema de certificados, os controles de animação tornaram praticamente numa ferramenta de
autoria multimídia, utilizando a potência da tecnologia DirectX.
Através do "HTML Layout Control", podemos criar paginas que fogem as limitações naturais do
HTML, com posicionamento preciso de imagens e objetos. ActiveX é a tecnologia que trará o poder
de processamento dos computadores pessoais as aplicações Internet/intranet. Fundamental para
todos os desenvolvedores.
Quais são os seus benefícios principais? • A possibilidade de criar conteúdos ativos e dinâmicos que atrairão mais visitantes às suas páginas.
• suporte desta tecnologia em várias plataformas que não apenas a plataforma Windows.
• A utilização de ferramentas de programação familiares e largamente divulgadas para desenvolver
os controles ActiveX.
• grande número de controles ActiveX já existentes e prontos a utilizar.
Quais são os elementos desta tecnologia? • Os controles ActiveX, ou seja, os objetos que se colocam em páginas HTML para proporcionar ao
utilizador funções interativas.
• Os documentos ActiveX que permitem ao utilizador visualizar documentos não-HTML num
browser.
• As scripts ActiveX que controlam o comportamento integrado de vários controles ActiveX e/ou
applets Java.
• A Java Virtual Machine que consiste do código que permite que um browser que suporte ActiveX,
seja capaz de integrar applets Java e controles ActiveX.
• A ActiveX Server Framework que proporciona um conjunto de funções ActiveX "server-based"
(baseadas no servidor).
ActiveX - Jurandir A Pellin 3
E a linguagem Java? • A grande diferença entre Java e ActiveX está no fato do Java ser uma linguagem de programação
enquanto o ActiveX é uma tecnologia de integração. Na verdade, estas são duas tecnologias
complementares e não concorrentes. Uma vez que a força do ActiveX se centra na integração de
objetos desenvolvidos em qualquer linguagem, permite tornar a linguagem Java ainda mais
poderosa, facilitando-lhe o acesso a código escrito em outras linguagens.
E quais são as grandes vantagens para os criadores de "Web sites"? • Por ser suportada e presente em várias ferramentas e linguagens de programação, o ActiveX
permite que programadores com experiências variadas transportem os seus conhecimentos para a
Web.
• Uma vez que já existem centenas de controles existentes e reutilizáveis, não será necessário aos
criadores começar tudo de novo cada vez que pretendam desenvolver objetos para o seu "Web site".
• Sendo uma tecnologia de integração, facilita a utilização de múltiplas linguagens de programação
em conjunto, com as vantagens de cada uma, para atingir um determinado objetivo.
Dois grandes Search Engines: Hotbot, eleito pela PC Magazine como o melhor do mundo, usa uma
alternativa de pesquisa com ActiveX que é bem melhor que a normal, o Infoseek criou um para
mostrar os assuntos e resultados da pesquisa em forma de árvore, facilitando o encontro do assunto
desejado. Ambos feitos no VB5.
ActiveX e VBScript O VBScript é uma versão leve do Visual Basic, tem limite para que não sejam criados programas
que causem dano ao usuário via Internet.
O VBScript não foi feito para concorrer com o Visual Basic, mas sim para ser uma solução para
pequenos e médios problemas, e principalmente "fazer funcionar" controles ActiveX, inicialmente
os que já vêm junto com o Internet Explorer, como o label, combo, list, image, hotspot,
webbrowser, etc.
O Macromedia Flash, um dos plugins mais promissores e festejados do momento, que está por trás
do show existente no site da Macromedia e MSN, na sua versão ActiveX pode não apenas executar
animações e fazer botões, mas ser controlado por vbscript, como voltar a animação, definir o nível
de qualidade e tudo que estamos acostumados a fazer com qualquer controle no VB, o que conta
muitos pontos, já que é tudo de maneira rápida, eficiente e sem quase nenhuma novidade para os
programadores, que automaticamente passam a desenvolver para a Web sem ter que aprender outra
linguagem, sem contar ainda que o Control Pad, VB5 CCE e o IE são gratuitos.
Quando se acessa uma página que contenha controles ActiveX, os mesmos são baixados para o
diretório ActiveX Cache do Windows, o Explorer se encarregando da instalação, o que não será
mais preciso nas próximas visitas ao site, já que o controle já estará no computador.
Para quem já conhece VB, o VBScript não terá muitas novidades, bastando ver apenas as
diferenças, limites que foram impostos e estudar sobre os novos objetos relativos ao browser.
Atualmente, ActiveX e VBScript só podem ser lidos pelo Internet Explorer da Microsoft, a
Netscape ficou em dúvida se apoiava ou não esta tecnologia, mas na versão 4 do seu browser
acabou optando pelo não.
ActiveX - Jurandir A Pellin 4
O que você precisa para trabalhar com ActiveX ? No site http://download.com.com/2001-2206-0.html baixe os programas ActiveX Control Pad (
cria arquivo ActiveX ) e o programa ActiveX Manger ( gerencia os controles ActiveX que estão na
sua máquina, podendo instalar ( registrar ) ou desistalar novos controles ). Na Internet existem
muitos outros controles ActiveX, basta baixá-los e registrá-los assim terá mais recursos para seu
desenvolvimento. Link com controles: http://cuinl.tripod.com/activex-2.htm
Configuração de controles ActiveX Muitas pessoas têm-me perguntado como resolver o problema do ActiveX quando uma mensagem
do tipo: "talvez não seja possível porque o ActiveX não está configurado de forma correta" aparece
quando abrem alguma página da Internet.
Notem que esta dica não se refere diretamente ao Outlook e, sim, ao Internet Explorer, mas que
afeta o Outlook.
Para configurar o AtiveX, proceda da seguinte maneira:
1.Abra seu Internet Explorer;
2.No menu Ferramentas do Internet Explorer, clique em Opções de Internet;
3.Clique na aba Segurança, selecione a zona de conteúdo Internet e depois clique no botão Nível Avançado (ou Personalizado);
ActiveX - Jurandir A Pellin 5
3. Localize o item Plug-ins e controles ActiveX;
4. Em "Controles de script ActiveX marcados como seguros para execução de scripts" clique em
Ativar;
5. Em "Executar controles ActiveX e plug-ins", marque Ativar;
6. Em "Fazer o download de controles ActiveX assinados", deixe clicado em Avisar;
7. Em "Fazer o download de controles ActiveX não assinados", marque Avisar;
8. Em "Inicializar e executar scripts de controles ActiveX não marcados como seguros", marque a
caixa Avisar.
Obs.: Preste bastante atenção quando for executar o controle ActiveX e só o execute em páginas nas
quais você confie. Quando receber algum aviso, pense duas vezes antes de executar. Para garantir-
se, tenha um bom anti-vírus instalado e atualizado em seu micro. Caso você seja muito desatento,
deixe as opções dos itens 7 e 8 clicadas em "Desativar".
Aproveite e confira as opções referentes a Script:
ActiveX - Jurandir A Pellin 6
9. Clique no botão Redefinir e depois em OK.
Prontinho! Aquelas mensagens não devem mais aparecer.
What's the difference between a horse trainer and a tailor? One tends a mare and one mends a
tear!
And now for another belly-chuckler - what's the difference between an ActiveX component and an ActiveX control?
OK, not quite a dinner party puzzler but still an important point. Let's take a look at what
exactly an ActiveX component is... and is not.
An ActiveX component is just a general term, encompassing:
• An ActiveX EXE
• An ActiveX DLL • An ActiveX Control
An ActiveX component is not:
• Active, in any way, shape or form • A source of fibre that can help you lose weight as part of a calorie controlled diet
So what exactly are ActiveX EXEs and DLLs? Basically, they're chunks of code you use in your
Visual Basic projects just by setting a reference to them — a little like how you set a reference
to DAO or ADO when you need access to a database.
But that's another department completely... more to the point, just what are ActiveX controls?
Well, you might not know this, but you already have experience of ActiveX controls. You've
used them, tweaked them and tossed them to one side — all in the course of a days work. Ohhhh yes.
Indeed, every time you set the Text property of a Text Box, you're utilising an ActiveX control.
Every time you respond to the Click event of a Command Button, you're utilising an ActiveX
control. Every time you run the MoveNext method of the Data control, you're utilising an ActiveX control.
I think you get the picture. In essence, an ActiveX control is anything you might see in the Toolbox.
Top Tip: Don't forget that you can also add more controls to the Toolbox by selecting Projects,
Components
ActiveX - Jurandir A Pellin 7
Exemplo 01 – Activex
01) Baixe o programa ActiveX Control Pad e instale-o ( http://download.com.com/2001-2206-
0.html )
02) Abra o programa ActiveX Control Pad
03) Clique em Edit, clique em Insert ActiveX Control, será mostrada uma caixa com os controles
ActiveX que estão no seu computador, escolha o controle Microsoft Forms 2.0 CommandButton
Após clicar no botão
OK será mostrada a
caixa abaixo com o
botão inserido e suas
propriedades.
ActiveX - Jurandir A Pellin 8
04) Defina as propriedades e evento do ( botão ) controle CommandButton
Na parte superior da caixa das Propriedades, ao lado do botão Aplicar, digite o texto Clique me 1,
este será mostrado no botão.
05) Propriedade – “BackColor” - cor de fundo do botão: dê um duplo na propriedade
BackColor, será aberta uma caixa para selecionar uma cor, após selecionado uma cor clique OK,
neste exemplo a cor Verde.
ActiveX - Jurandir A Pellin 9
06) Propriedade – “ForeColor” – cor da fonte – dê um clique duplo na propriedade ForeColor,
clique na cor amarela, veja ao lado o a cor do texto do botão e clique OK.
07) Propriedade – “Font” - Fonte: dê um clique duplo sobre Font, será aberta uma caixa, clique
em Negrito e clique OK.
ActiveX - Jurandir A Pellin 10
08) Feche as duas janelas, Edit ActiveX Control e a janela Propriedades. Após fechá-las note o
código ActiveX que foi gerado.
Código ActiveX que foi gerado, ou seja, todas as propriedades que definimos para o botão.
ActiveX - Jurandir A Pellin 11
09) Salve o arquivo:
10) Abra o arquivo e veja como ficou “até o momento”...
11) Alterando as propriedades
Clique no botão para
editar / alterar as
propriedades.
ActiveX - Jurandir A Pellin 12
12) Agora vamos inserir mais um controle, um Label.
Posicione o cursor onde deseja inserir o Label, veja abaixo:
13) Na barra de título clique em Edit, clique em Microsoft Forms 2.0 Label e clique OK.
Posicionei cursor
nesta região.
ActiveX - Jurandir A Pellin 13
Veja o Label incluído:
14) Clique na propriedade Caption, na parte superior das propriedades, ao lado do botão Aplicar
digite o texto mensagem
ActiveX - Jurandir A Pellin 14
15) Após fechar a tela Edit Activex Control será adicionado o código ActiveX no arquivo atual,
veja abaixo:
Veja como ficou a página:
16) Vamos definir eventos ( ações ), clique no ícone Script Wizard
Label
Botão
ActiveX - Jurandir A Pellin 15
17) Após clicar no Script Wizard será aberta a tela abaixo:
18) Clique no evento Click, clique
em Label1, clique em Caption,
clique no botão Insert Action e
digite o texto Meu primeiro
ActiveX , clique OK.
Veja o Botão e o Label
que já incluímos.
ActiveX - Jurandir A Pellin 16
19) Dê um clique duplo sobre BackColor para definir a cor de fundo da mensagem, será aberta uma
caixa para selecionar uma cor, selecione vermelho e clique OK.
20) Clique no botão Save para salvar.
21) Após clicar o botão Clique me 1, será trocado o texto mensagem por Meu primeiro ActiveX
e com fundo vermelho.
ActiveX - Jurandir A Pellin 17
Veja como ficou o código completo:
<HTML> <HEAD> <TITLE>New Page</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="VBScript"> <!-- Sub CommandButton1_Click() Label1.Caption = "Meu primeiro ActiveX" Label1.BackColor = &H000000FF end sub --> </SCRIPT> <OBJECT ID="CommandButton1" WIDTH=96 HEIGHT=32 CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57"> <PARAM NAME="ForeColor" VALUE="65535"> <PARAM NAME="BackColor" VALUE="4227072"> <PARAM NAME="Caption" VALUE="Clique me 1"> <PARAM NAME="Size" VALUE="2540;847"> <PARAM NAME="FontEffects" VALUE="1073741825"> <PARAM NAME="FontCharSet" VALUE="0"> <PARAM NAME="FontPitchAndFamily" VALUE="2"> <PARAM NAME="ParagraphAlign" VALUE="3"> <PARAM NAME="FontWeight" VALUE="700"> </OBJECT> <OBJECT ID="Label1" WIDTH=93 HEIGHT=27 CLASSID="CLSID:978C9E23-D4B0-11CE-BF2D-00AA003F40D0"> <PARAM NAME="Caption" VALUE="mensagem"> <PARAM NAME="Size" VALUE="2469;706"> <PARAM NAME="FontCharSet" VALUE="0"> <PARAM NAME="FontPitchAndFamily" VALUE="2"> </OBJECT> </BODY> </HTML>
ActiveX - Jurandir A Pellin 18
Exemplo 02
01) Inserir figura: Abra o programa Active Control Pad, feche a tela Page1, clique em File, New Html Layout. Clique na ferramenta Imagem, arraste-a até o formulário, dê um clique duplo na
propriedade Picture, será aberta uma caixa para selecionar uma imagem, selecione uma imagem e
clique OK para finalizar.
02) Salve o arquivo layout com sugerido ou digite o nome desejado.
ActiveX - Jurandir A Pellin 19
03) Cor de fundo do formulário: Definindo cor de fundo do formulário, clique duplo sobre o
formulário ( cor azul escura ), será aberta a caixa das propriedades, dê um clique duplo na opção
BackColor, será aberta uma caixa de cores, selecione a cor “azul escura” e clique OK para
finalizar.
04) Clique em File, New Html
05) Clique em Edit, Insert Html Layout, selecione o arquivo de layout que fizemos anteriormente:
ActiveX - Jurandir A Pellin 20
Note como ficou o código;
06) Salve a página com o nome de Page1_layout_1.htm
07) Abra a página Page1_layout_1.htm com um clique duplo, será pedido confirmação para
prosseguir.
Após ter inserido
Layout Html
ActiveX - Jurandir A Pellin 21
08) Rodando ActiveX - Computador Local ActiveX rodando máquina local
09) Rodando ActiveX - Internet Para rodar no servidor ( na net ) envie os dois arquivos Layout1.alx e Page1_layout_1.htm
São criados dois arquivos, o de � Layout que conterá imgens, botões, labels etc e o segundo
meramente será um arquivo � Html normal que irá ler o conteúdo do arquivo de layout e que será
o arquivo que irá rodar ( ser executado ).
ActiveX - Jurandir A Pellin 22
Exemplo 02
01) Abra o Activex Control Pad.
02) Clique em File – New Html Layout ( note que ao abrir o ActiveX Control Pad
automaticamente é aberta uma Page1 ( página html ), porém nós criaremos por primeiro uma página
de layout.
03) Clique em Label e arraste para o formulário, dê um clique duplo sobre o Label1 para definir as
propriedades deste objeto, clique em ID e altere o nome de Label1 para Lable1Idade ( a nomeação
deste objetos é importante para melhor identificá-los quando usarmos o Script Wizard ), clique em
Caption e digite Digite uma idade ( 10 - 30 ), ao invés de mostrar Label1 será mostrado Digite uma idade ( 10 - 30 ) que servirá para orientar o usuário.
04) Insira um Caixa de Texto, na propriedade ID mude para TextBox1Idade.
ActiveX - Jurandir A Pellin 23
05) Insira um Botão de Comando, altere as propriedades Caption para OK e ID para
CommandButton1OK.
Até o momento o formulário está assim, vamos programar para que seja aceita somente idade entre
10 a 30 anos
06) Clique em Script Wizard, clique em CommandButton1OK, clique Click, clique em Code View e abaixo de Sub CommandButton1OK_Click() digite o código que você está vendo ...
Clique em Code View e após digite
as linhas de código
ActiveX - Jurandir A Pellin 24
07) Salve o arquivo de Layout com o nome de Layout_um.alx ( a terminação DEVE ser .alx )
08) Após clique na página Page1, lembre no início deste projeto, quando abrimos o ActiveX
Control Pad automaticamente é aberta uma página Page1, pois bem, clique em Page1.
09) Clique em Edit, clique em Insert HTML Layout, clique no arquivo Layout_um.alx
ActiveX - Jurandir A Pellin 25
10) Após ter inserido arquivo Layout_um.alx
11) Salve o arquivo Page1 como o nome de Layout_um.htm, ou qualquer nome que desejar.
ActiveX - Jurandir A Pellin 26
12) Execute / rode o arquivo.
ActiveX - Jurandir A Pellin 27
Exemplos de códigos Visual Basic
ActiveX - Jurandir A Pellin 28
Mostra data em um Label
Veja mais na página
seguinte
ActiveX - Jurandir A Pellin 29
Creating customizable alert boxes using VBScript
No, we're not stabbing JavaScript in the back...just having a little harmless fun in this tutorial. The
entertainment? Customizable alert boxes.
In JavaScript, alert boxes are as simplistic- and dull- as they come:
alert("Hello there")
Apart from the message itself, nothing is changeable in terms of the box's interface. Where
JavaScript skims through, VBScript dwells on, however. Alert boxes called using the later language
can be customized in ways that the former can only dream of.
A basic alert box in VBScript is produced using the following code:
<script language="VBScript"> MsgBox "Hello there" </script>
From this point on, however, things take on a life of its own, thanks to the optional parameters the
above method supports. Case in point:
MsgBox "Hello there",64,"Greetings Jurandir"
Note the differing icon image to the left of the message, not to mention the title on top!
The below tables contain the supported values for the second parameter of MsgBox, which we'll
show first, then explain how to use: 'Which buttons" Table:
Constant Rendered button(s)
0 "Ok" button
1 "Ok" AND "Cancel" buttons
2 "Abort", 'Retry", AND "Ignore" buttons
3 "Yes", 'No", AND "Cancel" buttons
4 "Yes" AND "No" button
5 "Retry" AND "Cancel" button
ActiveX - Jurandir A Pellin 30
Default button table:
Constant Rendered button(s)
0 The first button from the left is the default button
256 The second button from the left is the default button
512 The third button from the left is the default button
768 The fourth button from the left is the default button
Icon image table:
Constant Rendered image
16
32
48
64
0 Blank
The above constants are interconnected and inseparable in their use. To specify which buttons and
icons to equip your VB Alert box with, add up the relevant constant in each table (in total three
constants), producing the parameter. Huh? For example, the box:
was produced using the parameter 0+0+64=64, since we wanted just an "Ok" button, that it be the
default one, and lastly, have the "exclamation" icon image shown.
Making sure the message is across, here's another VB box, rendered using:
MsgBox "Incorrect",37,"Greetings From JK"
5+0+32 is where the 37 was derived from.
ActiveX - Jurandir A Pellin 31
Do ... Until ... Loop
Imagem - Picture
ActiveX - Jurandir A Pellin 32
Inputbox
Label e Caption
ActiveX - Jurandir A Pellin 33
Case
InputBox – Cint – Soma
ActiveX - Jurandir A Pellin 34
Formatando data
InputBox – Label - &
ActiveX - Jurandir A Pellin 35
Dia da semana e o mês
Formatando mensagens
ActiveX - Jurandir A Pellin 36
If … Else – InputBox
Calculos ( multiplicar )
ActiveX - Jurandir A Pellin 37
Cint ( inteiro )
Month - Now
ActiveX - Jurandir A Pellin 38
Case – Month - Now
Formatando valor
ActiveX - Jurandir A Pellin 39
While … Wend
Do … While … Loop
ActiveX - Jurandir A Pellin 40
Do … Loop … Until
Day – Month – Year
ActiveX - Jurandir A Pellin 41
Validando campos Neste exemplo programamos o Evento Exit ( ao sair do campo Nome ), se este for vazio será
mostrada uma caixa de mensagem pedindo para digitar um Nome. No campo Sobrenome também
será verificado a digitação de um sobrenome. Ao clicar no botão Ok também será verificado
conteúdo dos campos
Evento do botão = OK
Quebra linha de
código.
ActiveX - Jurandir A Pellin 42
Evento caixa de texto = TextBox1 – Verifica se é digitado um Nome
Evento caixa de texto = TextBox2 – Verifica se é digitado um Sobrenome
ActiveX - Jurandir A Pellin 43
Alteração código acima. Validando os dois campos, se são digitados ou não.
ActiveX - Jurandir A Pellin 44
Somando
Resultado:
ActiveX - Jurandir A Pellin 45
Validando valores
ActiveX - Jurandir A Pellin 46
Funções do VBScript
Abs Array Asc Atn
CBool CByte CCur CDate
CDbl Chr CInt CLng
Conversions Cos CreateObject CSng
Date DateAdd DateDiff DatePart
DateSerial DateValue Day Derived Maths
Eval Exp Filter FormatCurrency
FormatDateTime FormatNumber FormatPercent GetLocale
GetObject GetRef Hex Hour
InputBox InStr InStrRev Int, Fixs
IsArray IsDate IsEmpty IsNull
IsNumeric IsObject Join LBound
LCase Left Len LoadPicture
Log LTrim; RTrim; and Trims Maths Mid
Minute Month MonthName MsgBox
Now Oct Replace RGB
Right Rnd Round ScriptEngine
ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion Second
SetLocale Sgn Sin Space
Split Sqr StrComp String
Tan Time Timer TimeSerial
TimeValue TypeName UBound UCase
VarType Weekday WeekdayName Year
Exemplos
InputBox Function
Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the
contents of the text box.
InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])
Arguments
prompt String expression displayed as the message in the dialog box. The maximum length of
prompt is approximately 1024 characters, depending on the width of the characters used. If
prompt consists of more than one line, you can separate the lines using a carriage return
character (Chr(13)), a linefeed character (Chr(10)), or carriage return–linefeed character
combination (Chr(13) & Chr(10)) between each line.
title String expression displayed in the title bar of the dialog box. If you omit title, the application
name is placed in the title bar.
default String expression displayed in the text box as the default response if no other input is
provided. If you omit default, the text box is displayed empty.
ActiveX - Jurandir A Pellin 47
xpos Numeric expression that specifies, in twips, the horizontal distance of the left edge of the
dialog box from the left edge of the screen. If xpos is omitted, the dialog box is horizontally
centered.
ypos Numeric expression that specifies, in twips, the vertical distance of the upper edge of the
dialog box from the top of the screen. If ypos is omitted, the dialog box is vertically
positioned approximately one-third of the way down the screen.
helpfile String expression that identifies the Help file to use to provide context-sensitive Help for the
dialog box. If helpfile is provided, context must also be provided.
context Numeric expression that identifies the Help context number assigned by the Help author to
the appropriate Help topic. If context is provided, helpfile must also be provided.
Remarks
When both helpfile and context are supplied, a Help button is automatically added to the dialog box.
If the user clicks OK or presses ENTER, the InputBox function returns whatever is in the text box.
If the user clicks Cancel, the function returns a zero-length string ("").
The following example uses the InputBox function to display an input box and assign the string to
the variable Input:
Dim Nome
Nome = InputBox("Digite seu nome")
MsgBox ("Você digitou: " & Nome)
MsgBox Function
Displays a message in a dialog box, waits for the user to click a button, and returns a value
indicating which button the user clicked.
MsgBox(prompt[, buttons][, title][, helpfile, context])
Arguments
prompt String expression displayed as the message in the dialog box. The maximum length of
prompt is approximately 1024 characters, depending on the width of the characters used. If
prompt consists of more than one line, you can separate the lines using a carriage return
character (Chr(13)), a linefeed character (Chr(10)), or carriage return–linefeed character
combination (Chr(13) & Chr(10)) between each line.
buttons Numeric expression that is the sum of values specifying the number and type of buttons to
display, the icon style to use, the identity of the default button, and the modality of the
message box. See Settings section for values. If omitted, the default value for buttons is 0.
ActiveX - Jurandir A Pellin 48
title String expression displayed in the title bar of the dialog box. If you omit title, the application
name is placed in the title bar.
helpfile String expression that identifies the Help file to use to provide context-sensitive Help for the
dialog box. If helpfile is provided, context must also be provided. Not available on 16-bit
platforms.
context Numeric expression that identifies the Help context number assigned by the Help author to
the appropriate Help topic. If context is provided, helpfile must also be provided. Not
available on 16-bit platforms.
Settings
The buttons argument settings are:
Constant Value Description
vbOKOnly 0 Display OK button only.
vbOKCancel 1 Display OK and Cancel buttons.
vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.
vbYesNoCancel 3 Display Yes, No, and Cancel buttons.
vbYesNo 4 Display Yes and No buttons.
vbRetryCancel 5 Display Retry and Cancel buttons.
vbCritical 16 Display Critical Message icon.
vbQuestion 32 Display Warning Query icon.
vbExclamation 48 Display Warning Message icon.
vbInformation 64 Display Information Message icon.
vbDefaultButton1 0 First button is default.
vbDefaultButton2 256 Second button is default.
vbDefaultButton3 512 Third button is default.
vbDefaultButton4 768 Fourth button is default.
vbApplicationModal 0 Application modal; the user must respond to the message
box before continuing work in the current application.
vbSystemModal 4096 System modal; all applications are suspended until the user
responds to the message box.
The first group of values (0–5) describes the number and type of buttons displayed in the dialog
box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512, 768)
determines which button is the default; and the fourth group (0, 4096) determines the modality of
the message box. When adding numbers to create a final value for the argument buttons, use only
one number from each group.
ActiveX - Jurandir A Pellin 49
Return Values
The MsgBox function has the following return values:
Constant Value Button
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
Remarks
When both helpfile and context are provided, the user can press F1 to view the Help topic
corresponding to the context.
If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking
Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog
box. However, no value is returned until one of the other buttons is clicked.
When the MsgBox function is used with Microsoft Internet Explorer, the title of any dialog
presented always contains "VBScript:" to differentiate it from standard system dialogs.
The following example uses the MsgBox function to display a message box and return a value
describing which button was clicked:
Dim Nome
Nome = MsgBox ("Ola Mundo!", 65, "Exemplo")
' Nome 1 ou 2 depedendo do botão que for pressinado.
CInt Function
Returns an expression that has been converted to a Variant of subtype Integer.
CInt(expression)
The expression argument is any valid expression.
Remarks
In general, you can document your code using the subtype conversion functions to show that the
result of some operation should be expressed as a particular data type rather than the default data
type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-
precision, or double-precision arithmetic normally would occur.
ActiveX - Jurandir A Pellin 50
Use the CInt function to provide internationally aware conversions from any other data type to an
Integer subtype. For example, different decimal separators are properly recognized depending on
the locale setting of your system, as are different thousand separators.
If expression lies outside the acceptable range for the Integer subtype, an error occurs.
The following example uses the CInt function to convert a value to an Integer:
Dim MyDouble, MyInt
MyDouble = 2345.5678 ' MyDouble is a Double.
MyInt = CInt(MyDouble) ' MyInt contains 2346.
Note CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional
part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the
nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.
String Constants
Since these constants are built into VBScript, you don't have to define them before using them. Use
them anywhere in your code to represent the values shown for each.
Constant Value Description
vbCr Chr(13) Carriage return.
VbCrLf Chr(13) & Chr(10) Carriage return–linefeed combination.
vbFormFeed Chr(12) Form feed; not useful in Microsoft Windows.
vbLf Chr(10) Line feed.
vbNewLine Chr(13) & Chr(10) or
Chr(10)
Platform-specific newline character; whatever is
appropriate for the platform.
vbNullChar Chr(0) Character having the value 0.
vbNullString String having value 0 Not the same as a zero-length string (""); used for calling
external procedures.
vbTab Chr(9) Horizontal tab.
vbVerticalTab Chr(11) Vertical tab; not useful in Microsoft Windows.
ActiveX - Jurandir A Pellin 51
Quebra linha com VbCr
Resultado
ActiveX - Jurandir A Pellin 52
Validando campos Neste exemplo programamos o Evento Exit ( ao sair do campo Nome ), se este for vazio será
mostrada uma caixa de mensagem pedindo para digitar um Nome. No campo Sobrenome também
será verificado a digitação de um sobrenome. Ao clicar no botão Ok também será verificado
conteúdo dos campos
Evento do botão = OK
Quebra linha de
código.
ActiveX - Jurandir A Pellin 53
Evento caixa de texto = TextBox1 – Verifica se é digitado um Nome
Evento caixa de texto = TextBox2 – Verifica se é digitado um Sobrenome
ActiveX - Jurandir A Pellin 54
Alteração código acima. Validando os dois campos, se são digitados ou não.
ActiveX - Jurandir A Pellin 55
Somando
ActiveX - Jurandir A Pellin 56
Validando valores
ActiveX - Jurandir A Pellin 57
Funções do VBScript
Abs Array Asc Atn
CBool CByte CCur CDate
CDbl Chr CInt CLng
Conversions Cos CreateObject CSng
Date DateAdd DateDiff DatePart
DateSerial DateValue Day Derived Maths
Eval Exp Filter FormatCurrency
FormatDateTime FormatNumber FormatPercent GetLocale
GetObject GetRef Hex Hour
InputBox InStr InStrRev Int, Fixs
IsArray IsDate IsEmpty IsNull
IsNumeric IsObject Join LBound
LCase Left Len LoadPicture
Log LTrim; RTrim; and Trims Maths Mid
Minute Month MonthName MsgBox
Now Oct Replace RGB
Right Rnd Round ScriptEngine
ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion Second
SetLocale Sgn Sin Space
Split Sqr StrComp String
Tan Time Timer TimeSerial
TimeValue TypeName UBound UCase
VarType Weekday WeekdayName Year
Exemplos
InputBox Function
Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the
contents of the text box.
InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])
Arguments
ActiveX - Jurandir A Pellin 58
prompt String expression displayed as the message in the dialog box. The maximum length of
prompt is approximately 1024 characters, depending on the width of the characters used. If
prompt consists of more than one line, you can separate the lines using a carriage return
character (Chr(13)), a linefeed character (Chr(10)), or carriage return–linefeed character
combination (Chr(13) & Chr(10)) between each line.
title String expression displayed in the title bar of the dialog box. If you omit title, the application
name is placed in the title bar.
default String expression displayed in the text box as the default response if no other input is
provided. If you omit default, the text box is displayed empty.
xpos Numeric expression that specifies, in twips, the horizontal distance of the left edge of the
dialog box from the left edge of the screen. If xpos is omitted, the dialog box is horizontally
centered.
ypos Numeric expression that specifies, in twips, the vertical distance of the upper edge of the
dialog box from the top of the screen. If ypos is omitted, the dialog box is vertically
positioned approximately one-third of the way down the screen.
helpfile String expression that identifies the Help file to use to provide context-sensitive Help for the
dialog box. If helpfile is provided, context must also be provided.
context Numeric expression that identifies the Help context number assigned by the Help author to
the appropriate Help topic. If context is provided, helpfile must also be provided.
Remarks
When both helpfile and context are supplied, a Help button is automatically added to the dialog box.
If the user clicks OK or presses ENTER, the InputBox function returns whatever is in the text box.
If the user clicks Cancel, the function returns a zero-length string ("").
The following example uses the InputBox function to display an input box and assign the string to
the variable Input:
Dim Nome
Nome = InputBox("Digite seu nome")
MsgBox ("Você digitou: " & Nome)
ActiveX - Jurandir A Pellin 59
MsgBox Function
Displays a message in a dialog box, waits for the user to click a button, and returns a value
indicating which button the user clicked.
MsgBox(prompt[, buttons][, title][, helpfile, context])
Arguments
prompt String expression displayed as the message in the dialog box. The maximum length of
prompt is approximately 1024 characters, depending on the width of the characters used. If
prompt consists of more than one line, you can separate the lines using a carriage return
character (Chr(13)), a linefeed character (Chr(10)), or carriage return–linefeed character
combination (Chr(13) & Chr(10)) between each line.
buttons Numeric expression that is the sum of values specifying the number and type of buttons to
display, the icon style to use, the identity of the default button, and the modality of the
message box. See Settings section for values. If omitted, the default value for buttons is 0.
title String expression displayed in the title bar of the dialog box. If you omit title, the application
name is placed in the title bar.
helpfile String expression that identifies the Help file to use to provide context-sensitive Help for the
dialog box. If helpfile is provided, context must also be provided. Not available on 16-bit
platforms.
context Numeric expression that identifies the Help context number assigned by the Help author to
the appropriate Help topic. If context is provided, helpfile must also be provided. Not
available on 16-bit platforms.
Settings
The buttons argument settings are:
Constant Value Description
vbOKOnly 0 Display OK button only.
vbOKCancel 1 Display OK and Cancel buttons.
vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.
vbYesNoCancel 3 Display Yes, No, and Cancel buttons.
vbYesNo 4 Display Yes and No buttons.
vbRetryCancel 5 Display Retry and Cancel buttons.
vbCritical 16 Display Critical Message icon.
vbQuestion 32 Display Warning Query icon.
vbExclamation 48 Display Warning Message icon.
vbInformation 64 Display Information Message icon.
vbDefaultButton1 0 First button is default.
vbDefaultButton2 256 Second button is default.
vbDefaultButton3 512 Third button is default.
ActiveX - Jurandir A Pellin 60
vbDefaultButton4 768 Fourth button is default.
vbApplicationModal 0 Application modal; the user must respond to the
message box before continuing work in the current
application.
vbSystemModal 4096 System modal; all applications are suspended until the
user responds to the message box.
The first group of values (0–5) describes the number and type of buttons displayed in the dialog
box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512, 768)
determines which button is the default; and the fourth group (0, 4096) determines the modality of
the message box. When adding numbers to create a final value for the argument buttons, use only
one number from each group.
Return Values
The MsgBox function has the following return values:
Constant Value Button
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
Remarks
When both helpfile and context are provided, the user can press F1 to view the Help topic
corresponding to the context.
If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking
Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog
box. However, no value is returned until one of the other buttons is clicked.
When the MsgBox function is used with Microsoft Internet Explorer, the title of any dialog
presented always contains "VBScript:" to differentiate it from standard system dialogs.
The following example uses the MsgBox function to display a message box and return a value
describing which button was clicked:
Dim Nome
Nome = MsgBox ("Ola Mundo!", 65, "Exemplo")
' Nome 1 ou 2 depedendo do botão que for pressinado.
ActiveX - Jurandir A Pellin 61
CInt Function
Returns an expression that has been converted to a Variant of subtype Integer.
CInt(expression)
The expression argument is any valid expression.
Remarks
In general, you can document your code using the subtype conversion functions to show that the
result of some operation should be expressed as a particular data type rather than the default data
type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-
precision, or double-precision arithmetic normally would occur.
Use the CInt function to provide internationally aware conversions from any other data type to an
Integer subtype. For example, different decimal separators are properly recognized depending on
the locale setting of your system, as are different thousand separators.
If expression lies outside the acceptable range for the Integer subtype, an error occurs.
The following example uses the CInt function to convert a value to an Integer:
Dim MyDouble, MyInt
MyDouble = 2345.5678 ' MyDouble is a Double.
MyInt = CInt(MyDouble) ' MyInt contains 2346.
Note CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional
part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the
nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.
ActiveX - Jurandir A Pellin 62
String Constants
Since these constants are built into VBScript, you don't have to define them before using them. Use
them anywhere in your code to represent the values shown for each.
Constant Value Description
vbCr Chr(13) Carriage return.
VbCrLf Chr(13) &
Chr(10)
Carriage return–linefeed combination.
vbFormFeed Chr(12) Form feed; not useful in Microsoft Windows.
vbLf Chr(10) Line feed.
vbNewLine Chr(13) &
Chr(10) or
Chr(10)
Platform-specific newline character; whatever is
appropriate for the platform.
vbNullChar Chr(0) Character having the value 0.
vbNullString String having
value 0
Not the same as a zero-length string (""); used for calling
external procedures.
vbTab Chr(9) Horizontal tab.
vbVerticalTab Chr(11) Vertical tab; not useful in Microsoft Windows.
Top Related