Search In Site

Showing posts with label Visual Basic Tutorials. Show all posts
Showing posts with label Visual Basic Tutorials. Show all posts

04 July, 2013

Working with Excel Files in VB

The code is totally self explanatory, In the load event we're going to open the new instance of the excel library and our excel file “book1.xls” will be accessible from our code. Then we'll use Command1 to retrieve data from book1, please note that you must have some data in the excel file. Similarly Command2 is used to put/replace the data in the excel sheet cells.
'do declare these variables you need to add a reference 
'to the microsoft excel 'xx' object library. 

 'you need two text boxes and two command buttons 
'on the form, an excel file in c:\book1.xls 
 Dim xl As New Excel.Application 
Dim xlsheet As Excel.Worksheet 
Dim xlwbook As Excel.Workbook 
 Private Sub Command1_Click() 
'the benifit of placing numbers in (row, col) is that you 
'can loop through different directions if required. I could 
'have used column names like "A1" 'etc. 
    Text1.Text = xlsheet.Cells(2, 1) ' row 2 col 1 
    Text2.Text = xlsheet.Cells(2, 2) ' row 2 col 2 
'don't forget to do this or you'll not be able to open 
'book1.xls again, untill you restart you pc. 
    xl.ActiveWorkbook.Close False, "c:\book1.xls" 
    xl.Quit 
End Sub 
Private Sub Command2_Click()
   xlsheet.Cells(2, 1) = Text1.Text
   xlsheet.Cells(2, 2) = Text2.Text
   xlwbook.Save 
'don't forget to do this or you'll not be able to open 
'book1.xls again, untill you restart you pc.
   xl.ActiveWorkbook.Close False, "c:\book1.xls"
   xl.Quit
End Sub
Private Sub Form_Load()
   Set xlwbook = xl.Workbooks.Open("c:\book1.xls")
   Set xlsheet = xlwbook.Sheets.Item(1)
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set xlwbook = Nothing
Set xl = Nothing
End Sub

How to Add Disappearing Effect To Forms in Visual Basic

This code demonstrates the use of SetLayeredWindowAttributes, GetWindowLong& SetWindowLong API calls. You need a timer on the form called "Timer1". Timer1 is enabled by default, so with the Load Event of the form it'll start ticking....
It'll make the form more transparent with each tick. 255 means no transparency, 0 means 100% transparent. When the form is 100% transparent Timer1 will unload it and load the "Main" form (I assume frmMain is the Main Form or any form you want to show after unloading it).
The only problem with this code is that Windows98 & ME does not support SetLayeredWindowAttributes API, so it won't work on these Operating Systems. You can use GetVersionEx API to determine the OS Version....
Copy the code below in the form you want to add the effect to.


Option Explicit
Dim Trans As Integer
Private Const LWA_COLORKEY = 1
Private Const LWA_ALPHA = 2
Private Const LWA_BOTH = 3
Private Const WS_EX_LAYERED = &H80000
Private Const GWL_EXSTYLE = -20
Private Declare Function SetLayeredWindowAttributes Lib "user32" _
(ByVal hwnd As Long, ByVal color As Long, ByVal x As Byte, _
ByVal alpha As Long) As Boolean
Private Declare Function SetWindowLong Lib "user32" Alias _
"SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, _
ByVal dwNewLong As Long) As Long
Private Declare Function GetWindowLong Lib "user32" Alias _
"GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Sub SetTrans(hwnd As Long, Trans As Integer)
Dim Tcall As Long
Tcall = GetWindowLong(hwnd, GWL_EXSTYLE)
SetWindowLong hwnd, GWL_EXSTYLE, Tcall Or WS_EX_LAYERED
SetLayeredWindowAttributes hwnd, RGB(255, 255, 0), Trans, LWA_ALPHA
Exit Sub
End Sub
Private Sub Form_Load()
frmMain.Show
frmMain.Enabled = False
Timer1.Interval = 1
Trans = 255
SetTrans Me.hwnd, Trans
End Sub
Private Sub Timer1_Timer()
If Trans <> 0 Then
Trans = Trans - 1
End If
SetTrans Me.hwnd, Trans
If Trans = 0 Then
frmMain.Enabled = True
Unload Me
End If
End Sub

How to create dynamic Menu In Vb

Dynamic Menu Form coding
Option Explicit
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
lblLabel.BackColor = vbButtonFace
lblLabel.ForeColor = vbWindowText
End Sub
Private Sub lblLabel_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
lblLabel.BackColor = vbHighlight
lblLabel.ForeColor = vbHighlightText
End Sub
Private Sub lblLabel_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim oMenu As mcPopupMenu: Set oMenu = New mcPopupMenu
Dim oSubmenu1 As mcPopupMenu: Set oSubmenu1 = New mcPopupMenu
Dim oSubmenu2 As mcPopupMenu: Set oSubmenu2 = New mcPopupMenu
Dim oSubmenu3 As mcPopupMenu: Set oSubmenu3 = New mcPopupMenu
Dim x1 As Single, y1 As Single, Ret As Long
' Labels don't have a handle, set x,y manually
x1 = (Me.Left + 45 + lblLabel.Left) / 15 ' 15 twips per pixel
y1 = (Me.Top + 525 + lblLabel.Height) / 15
' Add a few of the main menu items
oMenu.Add 1, "Item 1"
oMenu.Add 2, "Item 2", True, , , imglstImages.ListImages(1).Picture
oMenu.Add 3, "Item 3", , , mceGrayed
oMenu.Add 4, "-" ' Seperator
' Build our submenus when needed
oSubmenu1.Caption = "Submenu 1"
oSubmenu1.Add 20, "Submenu 1 Item 1", , , mceGrayed, imglstImages.ListImages(2).Picture
oSubmenu1.Add 21, "Submenu 1 Item 2", , , , imglstImages.ListImages(3).Picture
oSubmenu1.Add 22, "Submenu 1 Item 3", , , , imglstImages.ListImages(4).Picture

' Submenu of the first submenu
oSubmenu2.Caption = "Submenu 2"
oSubmenu2.Add 30, "Submenu 2 Item 1"
oSubmenu2.Add 31, "Submenu 2 Item 2"
oSubmenu2.Add 32, "Submenu 2 Item 3"
' Add second submenu to first
oSubmenu1.Add 33, oSubmenu2

' Add first submenu to main.
oMenu.Add 5, oSubmenu1
oMenu.Add 6, "-" ' Another seperator

' Build third submenu
oSubmenu3.Caption = "Submenu 3"
oSubmenu3.Add 40, "Submenu 2 Item 1", , , , imglstImages.ListImages(2).Picture
oSubmenu3.Add 41, "Submenu 3 Item 2", , , , imglstImages.ListImages(3).Picture
oSubmenu3.Add 42, "Submenu 3 Item 3", , , , imglstImages.ListImages(4).Picture
oMenu.Add 7, oSubmenu3
oMenu.Add 8, "-" ' Yet another

' The remaining items in the main menu
oMenu.Add 9, "Item 4", , True
oMenu.Add 10, "Item 5", , , , imglstImages.ListImages(4).Picture
oMenu.Add 11, "Item 6", , True, mceGrayed

' Show popup
Ret = oMenu.Show(Me.Hwnd, x1, y1)
' Release objects
Set oSubmenu1 = Nothing: Set oSubmenu2 = Nothing: Set oSubmenu3 = Nothing: Set oMenu = Nothing
    MsgBox "You chose menu ID " & Ret
    Select Case Ret
 ' Lights, camera, action!
End Select
End Sub

Dynamic Menu Class coding
Option Explicit
Private Declare Function GetLastError Lib "kernel32.dll" () As Long
' Exposed Enumeration
Public Enum mceItemStates
mceDisabled = 1
mceGrayed = 2
End Enum
' Property variables
Private psCaption As String ' Caption of menu item (with the arrow >) if this is submenu
Private piHwnd As Long ' Handle to Menu
' Supporting API code
Private Const GW_CHILD = 5
Private Const GW_HWNDNEXT = 2
Private Const GW_HWNDFIRST = 0
Private Const MF_BYCOMMAND = &H0&
Private Const MF_BYPOSITION = &H400
Private Const MF_CHECKED = &H8&
Private Const MF_DISABLED = &H2&
Private Const MF_GRAYED = &H1&
Private Const MF_MENUBARBREAK = &H20&
Private Const MF_MENUBREAK = &H40&
Private Const MF_POPUP = &H10&
Private Const MF_SEPARATOR = &H800&
Private Const MF_STRING = &H0&
Private Const MIIM_ID = &H2
Private Const MIIM_SUBMENU = &H4
Private Const MIIM_TYPE = &H10
Private Const TPM_LEFTALIGN = &H0&
Private Const TPM_RETURNCMD = &H100&
Private Const TPM_RIGHTBUTTON = &H2

Private Type POINT
X As Long
Y As Long
End Type
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Type MENUITEMINFO
cbSize As Long
fMask As Long
fType As Long
fState As Long
wID As Long
hSubMenu As Long
hbmpChecked As Long
hbmpUnchecked As Long
dwItemData As Long
dwTypeData As String
cch As Long
End Type
Private Declare Function AppendMenu Lib "user32" Alias "AppendMenuA" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long, lpNewItem As String) As Long
Private Declare Function DestroyMenu Lib "user32" (ByVal hMenu As Long) As Long
Private Declare Function DeleteMenu Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal uFlags As Long) As Long
Private Declare Function CreatePopupMenu Lib "user32" () As Long
Private Declare Function EnableMenuItem Lib "user32" (ByVal hMenu As Long, ByVal wIDEnableItem As Long, ByVal wEnable As Long) As Long
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINT) As Long
Private Declare Function GetDesktopWindow Lib "user32" () As Long
Private Declare Function GetWindow Lib "user32" (ByVal Hwnd As Long, ByVal wCmd As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal Hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function GetCurrentProcessId Lib "kernel32" () As Long
Private Declare Function GetWindowRect Lib "user32" (ByVal Hwnd As Long, lpRect As RECT) As Long
Private Declare Function GetMenuItemInfo Lib "user32" Alias "GetMenuItemInfoA" (ByVal hMenu As Long, ByVal un As Long, ByVal b As Boolean, lpMenuItemInfo As MENUITEMINFO) As Boolean
Private Declare Function GetFocus Lib "user32" () As Long
Private Declare Function GetForegroundWindow Lib "user32" () As Long
Private Declare Function SetMenuDefaultItem Lib "user32" (ByVal hMenu As Long, ByVal uItem As Long, ByVal fByPos As Long) As Long
Private Declare Function TrackPopupMenuEx Lib "user32" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal X As Long, ByVal Y As Long, ByVal Hwnd As Long, ByVal lptpm As Any) As Long
Private Declare Function SetMenuItemBitmaps Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long, ByVal hBitmapUnchecked As Long, ByVal hBitmapChecked As Long) As Long
Private Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, ByVal yPoint As Long) As Long
Public Property Let Caption(ByVal sCaption As String)
psCaption = sCaption
End Property
Public Property Get Caption() As String
    Caption = psCaption
End Property


Public Sub Remove(ByVal iMenuPosition As Long)
    DeleteMenu piHwnd, iMenuPosition, MF_BYPOSITION
End Sub
Private Sub Class_Initialize()
piHwnd = CreatePopupMenu()
End Sub
Private Sub Class_Terminate()
DestroyMenu piHwnd
End Sub
Public Property Get Hwnd() As Long
    Hwnd = piHwnd
End Property
Public Sub Add(ByVal iMenuID As Long, vMenuItem As Variant, Optional bDefault As Boolean = False, Optional bChecked As Boolean = False, Optional eItemState As mceItemStates, Optional ByVal imgUnchecked As Long = 0, Optional ByVal imgChecked As Long = 0)
    
' Check to see if it's a menu item (a string) or a submenu (a class).
       If TypeName(vMenuItem) = "String" Then
       If vMenuItem = "-" Then ' Make a seperator
AppendMenu piHwnd, MF_STRING Or MF_SEPARATOR, iMenuID, ByVal vbNullString
Else
AppendMenu piHwnd, MF_STRING Or -bChecked * MF_CHECKED, iMenuID, ByVal vMenuItem
End If
' Menu Icons
If imgChecked = 0 Then imgChecked = imgChecked ' Need a value for both
SetMenuItemBitmaps piHwnd, iMenuID, MF_BYCOMMAND, imgUnchecked, imgChecked

' Default item
If bDefault Then SetMenuDefaultItem piHwnd, iMenuID, 0
' Disabled (Regular color text)
If eItemState = mceDisabled Then EnableMenuItem piHwnd, iMenuID, MF_BYCOMMAND Or MF_DISABLED
' Disabled (disabled color text)
If eItemState = mceGrayed Then EnableMenuItem piHwnd, iMenuID, MF_BYCOMMAND Or MF_GRAYED
' Add a submenu
ElseIf TypeOf vMenuItem Is mcPopupMenu Then
Dim oSubmenu As mcPopupMenu: Set oSubmenu = vMenuItem
AppendMenu piHwnd, MF_STRING Or MF_POPUP, oSubmenu.Hwnd, ByVal oSubmenu.Caption
Set oSubmenu = Nothing
End If
End Sub

Public Function Show(Optional ByVal iFormHwnd As Long = -1, Optional ByVal X As Long = -1, Optional ByVal Y As Long = -1, Optional ByVal iControlHwnd As Long = -1) As Long
Dim iHwnd As Long, iX As Long, iY As Long
    ' If no form is passed, use the current window
If iFormHwnd = -1 Or iFormHwnd = 0 Then
        Dim iDesktopHwnd As Long, iChildHwnd As Long, iCurrentID As Long, iChildID As Long
        iDesktopHwnd = GetDesktopWindow()
iChildHwnd = GetWindow(iDesktopHwnd, GW_CHILD)
iCurrentID = GetCurrentProcessId()
Do While iChildHwnd
GetWindowThreadProcessId iChildHwnd, iChildID
If iChildID = iCurrentID Then Exit Do ' Snagged
iChildHwnd = GetWindow(iChildHwnd, GW_HWNDNEXT)
Loop
        If iChildHwnd = 0 Then ' Can't resolve a form handle. Bail out.
Show = -1
Exit Function
End If
iHwnd = iChildHwnd
Else
iHwnd = iFormHwnd
End If
    ' If passed a control handle, left-bottom orient to the control.
If iControlHwnd <> -1 Then
Dim rt As RECT
GetWindowRect iControlHwnd, rt
iX = rt.Left
iY = rt.Bottom
Else
Dim pt As POINT
GetCursorPos pt
If X = -1 Then iX = pt.X Else: iX = X
If Y = -1 Then iY = pt.Y Else: iY = Y
End If
Show = TrackPopupMenuEx(piHwnd, TPM_RETURNCMD Or TPM_RIGHTBUTTON, iX, iY, iHwnd, ByVal 0&)
End Function

03 July, 2013

Visual Basic Statements and Expressions


Visual Basic Statements and Expressions
·  The simplest statement is the assignment statement. It consists of a variable name, followed by the assignment operator (=), followed by some
sort of expression.
Examples:
StartTime = Now
Explorer.Caption = "Captain Spaulding"
BitCount = ByteCount * 8
Energy = Mass * LIGHTSPEED ^ 2
NetWorth = Assets - Liabilities
The assignment statement stores information.
· Statements normally take up a single line with no termi nator. Statements can be stacked by using a colon (:) to separate them. Example:
StartTime = Now : EndTime = StartTime + 10
(Be careful stacking statements, especially with If/End If structures. You may not get the response you desire.)
· If a statement is very long, it may be continued to the next line using the
continuation character, an underscore (_). Example:
Months = Log(Final * IntRate / Deposit + 1) _
/ Log(1 + IntRate)
·  Comment statements begin with the keyword Rem or a single quote ('). For
example:
Rem This is a remark
' This is also a remark
x = 2 * y ' another way to write a remark or comment
You, as a programmer, should decide how much to comment your code.
Consider such factors as reuse, your audience, and the legacy of your code.

How to create PDF file from Visual Basic


How to create PDF file from Visual Basic
: example "Hello, PDF!"
This page contatins step-by-step tutorial aimed to teach you how to createPDFfile from Visual Basic application using PDF Creator Pilot library.
1)InstallPDF Creator Pilotlibrary on your computer and runVisual Basic.
You will see New Project Wizard:
2)SelectStandard EXEproject type and clickOpento create new project.
Visual Basic will generate new projectProject1and will automatically open the main form of the generated project:
3)Now we should place a button that will launchl PDF generation function. To place the button just clickCommandButtonon the controls toolbar on the left:
Now press your right mouse button and then drag the mouse so you will set the rectangle for a new control and release the mouse button to create the control. It will look like this:
4)Visual Basic will create new button control on theForm1. Double-click on the control to letVisual Basiccreate the click handler function in the project code: Visual Basicwill create new function which will be launched every time when user clicks the button:
5)Now you have to write the code that will generate PDF file using PDF Creator Pilot . 
To generate PDF document you have to do the following:
1.connect to the PDF Creator Pilot library;
2.set the filename for PDF document;
3.draw "Hello, PDF!" message on the PDF page;
4.disconnect from the library.
Here is the source code:
Private Sub Command1_Click()
’ connect to library
SetPDF = CreateObject("PDFCreatorPilot.piPDFDocument")
’ initialize PDF Engine
PDF.StartEngine "demo@demo", "demo"
’ set PDF ouput filename
PDF.FileName = "HelloPDF_VB.pdf"
PDF.AutoLaunch = True’ auto-open generated pdf document
’ start document generation
PDF.BeginDoc
’ draw "HELLO, PDF" message on the current PDF page
PDF.PDFPAGE_BeginText
PDF.PDFPAGE_SetActiveFont "Verdana", True, False, False, False, 14, 0
PDF.PDFPAGE_TextOut 10, 20, 0, "HELLO, PDF!"
PDF.PDFPAGE_EndText
’ finalize document generation
PDF.EndDoc
’ disconnect from library
SetPDF = Nothing
End Sub
This function will generate PDF document and save it as "HelloPDF_VB.PDF"file in the application’s folder.
Hint:
You can simply copy the source code from the snippet above and then paste it in theVisual Basiccode editor as it’s shown on the
screenshot below:
6)PressF5to run the application (you can also use "Run" | "Start" menu command).
Visual Basic will run the application and you will see its main form:
7)Click "Command1" button and application will generate"HelloPDF_VB.PDF"file.
If you have any PDF viewer (for example,Adobe Acrobat Reader) installed on your computer then the library will launch it to open
the generated PDF document:
You can find the source code of this example in the"\Examples\VB\"sub-folder.

01 July, 2013

Organise your first project In Visual Basic


Organising your first project
The first step is to create a project template within VB, to organise and store your work. This will consist of a menu structure with headings that will let you access the many exercises and examples you complete.
Activity 1
·  Open VisualBasic 6.0
·  Use the file menu to open a new project with a blank form.
·  Use the properties window to set
– Main.frm as the form name.
– My programs as the caption.
– BackColor to White.
– BorderStyle to Fixed Single.
– WindowState to Maximised.
·  Find the Menu icon and click on it to select it. Enter the following menu headings:
Quit
Introduction with indented subheadings of Example1 , Example2
Click OK after each menu caption and name are typed.
·  Click on Quit menu heading and enter the following code. This procedure is used to exit from running the project display and return to the design screens.
Private Sub Quit_Click()
Unload me
End
End Sub
·  Use the <F5> function key to run the application to verify that the Menu structure is correct and that the Quit procedure is free from error.
·  Use the File menu to save your work as Main.frm and (your intitials)Project1.vbp
·  Use the file menu to open a new blank form (or the properties window)
·  Set the following form properties:
form name as Welcome caption to Example1 BackColor to White BorderStyle to Fixed Single

WindowState to Maximised
·  Click on the Example 1 main menu heading and enter the following code:
Private Sub Example1_Click()
Welcome.Show
End Sub
·  Save your work and run <F5> to ensure that it is free of errors.
·  Add two labels, an image and a command button to create a welcome screen. To do this Select label icon from the toolbox. Click towards the centre-top of your form and position and resize your label as required. With the label selected, use the properties window to Change the caption to WELCOME TO VISUAL BASIC

Choose a bright back colour
Set the font (Arial, underline, alignment centred, size 24 point, forecolour blue) 
Repeat to add the Enjoy label.
Use the image icon on your toolbox to add the image to your form. Use the
properties window of the image to select a picture. Use the command Button icon to add the button. Change its caption to RETURN. Then double-click the button and add the following line of code after the Command1_Click() procedure.
– Unload Welcome
·  Use the file menu to save your work and use <F5> to run the application.
·  DON’T FORGET TO SAVE (AND BACK UP TO FLOPPY) ALL YOUR WORK.
Event handlers and scroll bars Some definitions to learn
·  An object is a thing  anything that appears on the screen. An object has a set of properties. Each property of the object has a value.
e.g. Label.Caption = “Welcome to Visual Basic” where
Label is an object

Caption is a property of label
“Welcome to Visual Basic” is a value of the Caption property.
·  Events are things that happen on the screen. Event handlers transfer data to procedures that complete the task. The results of these procedures are returned back to other screen objects, e.g. onChange onClick 
·  A procedure is a group of statements designed to perform a specific task. A
procedure attached to an object, such as a button, is a command used to make something happen, e.g.
Public Sub Command2_Click()
Text1.Text = “This is a procedure.”
End Sub

Add new form to menu
As each new example and exercise solution is to be added to your project you will need to:
·  add a new form
·  set the form properties using the properties window
·  click on the main menu icon with the main form displayed to show the menu
designer
·  add a new menu heading
·  click on the menu heading to show the procedure code
·  to the procedure code, add the statement
FormXX.Show
where FormXX is the new form name.
Activity 2
1. Open a new form and change its name to ColourChanger. Place the following objects on this form.
 A heading label2 (Caption = Colour Changer)
 3 horizontal scroll bars (Set the max value property of all three to 255)
 3 other labels (2red, 3Green, 4Blue)  a command button to quit the form (Caption = Return)  another small label5 under the button with its visible property set to false.
2. Double click each scroll bar and add the following code to its _onChange() event. Use cut and paste to make the task easier.
Label1.BackColor = RGB(HScroll1.Value, HScroll2.Value, HScroll3.Value)
Label5.BackColor = RGB(HScroll1.Value, HScroll2.Value, HScroll3.Value)
Label1.ForeColor = RGB(255 - HScroll1.Value, 255 - HScroll2.Value, 255 -
HScroll3.Value)
Label5.ForeColor = RGB(255 - HScroll1.Value, 255 - HScroll2.Value, 255 -
HScroll3.Value)
Label5.Visible = True
Label5.Caption = “WOW!”
Label2.BackColor = RGB(HScroll1.Value, 0, 0)
Label3.BackColor = RGB(0, HScroll2.Value, 0)
Label4.BackColor = RGB)0, 0, HScroll3.Value)
3. Double click the return button and add the following code to its _onClick() event
Unload Me
4. Use the Project Explorer window to return to your main form and double click
example 2 in your menu to add the appropriate code.
5. Use <F5> function key to test your project. Save and backup.

Blurring And Sweeping Images in Visual Basic


Sweeping Images
When we created embossed and engraved images in the previous two topics, we were careful to set up our embossing or engraving loop so that when setting a pixel, we did not make use of other pixels that we had already
set in the same loop. 
The reason for that is that we only wanted to plot the difference between adjacent pixels that is, the difference between two pixels only to create embossed or engraved images. If we had not restricted our operation to two pixels we had not already worked on, and instead worked on pixels we had already set earlier, we could end up propagating a pixel’s color values among several other pixels. That is, one pixel’s setting could affect many other pixels.
In fact, there are times when you want to have that happen—for example, you might want to make an image appear as though it is sweeping from upper-left to lower-right, giving the illusion of motion. In that case, you’d copy pixels with the ones to the upper-left over and over, progressively blending them together to create the effect, where it looks as though the text has a fading trail of color behind it.
we move from lower-right to upper-left, averaging each pixel with the one to the lower-right:
For x = intUpperBoundX – 1 To 1 Step –1
For y = intUpperBoundY – 1 To 1 Step –1
bytRed = Abs((Pixels(x + 1, y + 1) And &HFF) + (Pixels(x, y)_
And &HFF)) / 2
bytGreen = Abs(((Pixels(x + 1, y + 1) And &HFF00) / &H100)_
Mod &H100 + ((Pixels(x, y) And &HFF00) / &H100) Mod_
&H100) / 2
bytBlue = Abs(((Pixels(x + 1, y + 1) And &HFF0000) / &H10000) _
Mod &H100 + ((Pixels(x, y) And &HFF0000) / &H10000) Mod_
&H100) / 2
Pixels(x, y) = RGB(bytRed, bytGreen, bytBlue)
Next y
Next x
That’s all it takes—now we copy the image into the second picture box,  picture2. (To be able to work pixel by pixel, make sure you set each picture box’s ScaleMode property to vbPixel (3).) By combining successive pixels
as we do in this example, we create the sweeping effect. Now we’re creating complex images using image handling techniques. 

Blurring Images
The Aesthetic Design Department is calling again. If you’re going to add image effects to your program, SuperDuperGraphicsPro, why not let the user blur images? You can blur images by averaging pixels. To see how this works, we load the pixels from a picture box, Picture1, and blur them, then display the result in another picture box, Picture2. To be able to work pixel by pixel, set each picture box’s ScaleMode property to vbPixel (3). As with the code in the previous few topics in this chapter, we load the pixels from Picture1 into an array named Pixels. To blur the pixels, you average them together; here, we just average each pixel with the next pixel to the right , but you can set up any blurring region you like (such as all eight pixels that surround the  current pixel). This is the way our blurring process looks in code:
For x = 1 To intUpperBoundX – 1
For y = 1 To intUpperBoundY
bytRed = Abs((Pixels(x + 1, y) And &HFF) + (Pixels(x, y) _
And &HFF)) / 2
bytGreen = Abs(((Pixels(x + 1, y) And &HFF00) / &H100) Mod _
&H100 + ((Pixels(x, y) And &HFF00) / &H100) Mod &H100) / 2
bytBlue = Abs(((Pixels(x + 1, y) And &HFF0000) / &H10000) _
Mod &H100 + ((Pixels(x, y) And &HFF0000) / &H10000)_
Mod &H100) / 2
Pixels(x, y) = RGB(bytRed, bytGreen, bytBlue)
Next y
Next x

How to Create Grayscale And lightening Images in Vb


Creating Grayscale Images
We’ve seen how to work with images bit by bit in the previous topic. We’ll augment that in this topic, where we see how to convert color images to grayscale images. We do this by reading an image into a pixel array, then by converting each of those pixels to gray and writing the pixel array out to a new image. Let’s see how this works. We’ll convert the image in a picture box, Picture1, to grayscale, and display it in a new picture box, Picture2, when the user clicks a command button, Command1. To be able to work pixel by pixel, set each picture box’s ScaleMode property to vbPixel (3).
First, we set up storage space for the image in an array named Pixels, declared in the form’s (General) section:
Const intUpperBoundX = 300
Const intUpperBoundY = 300
Dim Pixels(1 To intUpperBoundX, 1 To intUpperBoundY) As Long
When the user clicks the command button, we store the image in Picture1 into the array Pixels:
Private Sub Command1_Click()
Dim x, y As Integer
For x = 1 To intUpperBoundX
For y = 1 To intUpperBoundY
Pixels(x, y) = Picture1.Point(x, y)
Next y
Next x
Now we’re free to work with the image’s pixels in a new loop (to be efficient, this new loop should be incorporated into the first loop where we read the pixels in, but here we’ll use a new loop to make the image-handling process clear). In that new loop, we first separate out the color values (red, green, and
blue) for each pixel. To create a grayscale image, you average those color values and then use the resulting average as the red, green, and blue color values in the new image. The Point method returns a Long integer holding the red, green, and blue color values (which range from 0 to 255) in hexadecimal: &HBBGGRR. That means we can separate out the red, green, and blue color
values, storing them as the bytes bytRed, bytGreen, and bytBlue this way:
Private Sub Command1_Click()
Dim x, y As Integer
Dim bytRed, bytGreen, bytBlue As Integer
For x = 1 To intUpperBoundX
For y = 1 To intUpperBoundY
Pixels(x, y) = Picture1.Point(x, y)
Next y
Next x
For x = 1 To intUpperBoundX
For y = 1 To intUpperBoundY
bytRed = Pixels(x, y) And &HFF
bytGreen = ((Pixels(x, y) And &HFF00) / &H100) Mod &H100
bytBlue = ((Pixels(x, y) And &HFF0000) / &H10000) Mod &H100

To convert each pixel to grayscale, we just average its color values. Finally, we display the new image in a second picture box, Picture2:
Private Sub Command1_Click()
Dim x, y As Integer
Dim bytRed, bytGreen, bytBlue, bytAverage As Integer

For x = 1 To intUpperBoundX
For y = 1 To intUpperBoundY
bytRed = Pixels(x, y) And &HFF
bytGreen = ((Pixels(x, y) And &HFF00) / &H100) Mod &H100
bytBlue = ((Pixels(x, y) And &HFF0000) / &H10000) Mod &H100
bytAverage = (bytRed + bytGreen + bytBlue) / 3
Pixels(x, y) = RGB(bytAverage, bytAverage, bytAverage)
Next y
Next x
For x = 1 To intUpperBoundX
For y = 1 To intUpperBoundY
Picture2.PSet (x, y), Pixels(x, y)
Next y
Next x
End Sub

Lightening Images
The Testing Department is calling. Some of the users of your  super Duper Graphics Pro program are saying the images in that program are too dark—can you let them lighten them? Hmm, you think ,how does that work? You can lighten images by adding the same positive number to each color value (red, green, and blue) of each pixel. Let’s see how this works in an example. Here, we’ll take the image in a picture box, Picture1, and add a value specified by the user to each color value when the user clicks a command button, Command1, displaying the result in a second picture box, Picture2. To be able to work pixel by pixel, set each picture box’s ScaleMode property to vbPixel (3). We’ll also have a text box, Text1, that will hold the value the user wants to add to each color value to lighten it. We start by setting up the storage we’ll need for the image:
Const intUpperBoundX = 200
Const intUpperBoundY = 200
Dim Pixels(1 To intUpperBoundX, 1 To intUpperBoundY) As Long
Next, we place the value the user wants added to each color value in a new variable named intAddOn when the user clicks the command button:
Private Sub Command1_Click()
Dim intAddOn As Integer
intAddOn = Val(Text1.Text)
Now we read the image in Picture1 into the array named Pixels:
Private Sub Command1_Click()
Dim x, y, intAddOn As Integer
intAddOn = Val(Text1.Text)
For x = 1 To intUpperBoundX
For y = 1 To intUpperBoundY
Pixels(x, y) = Picture1.Point(x, y)
Next y
Next x
Next, we get the red, green, and blue color values for each pixel and add the value in intAddOn to those color values, making sure they don’t go higher than 255 (of course, you can also darken images by subtracting values here, although you should make sure the resulting color values don’t go below 0):
Private Sub Command1_Click()
Dim x, y, intAddOn As Integer
Dim bytRed, bytGreen, bytBlue As Integer

For x = 1 To intUpperBoundX
For y = 1 To intUpperBoundY
bytRed = Pixels(x, y) And &HFF
bytGreen = ((Pixels(x, y) And &HFF00) / &H100) Mod &H100
bytBlue = ((Pixels(x, y) And &HFF0000) / &H10000) Mod &H100
bytRed = bytRed + intAddOn
If bytRed > 255 Then bytRed = 255
bytGreen = bytGreen + intAddOn
If bytGreen > 255 Then bytGreen = 255
bytBlue = bytBlue + intAddOn
If bytBlue > 255 Then bytBlue = 255
Pixels(x, y) = RGB(bytRed, bytGreen, bytBlue)
Next y
Next x
End Sub
Finally, we just copy the new pixels to the second picture box, Picture2:
Private Sub Command1_Click()
Dim x, y, intAddOn As Integer

For x = 1 To intUpperBoundX
For y = 1 To intUpperBoundY
Picture2.PSet (x, y), Pixels(x, y)
Next y
Next x
End Sub

How to Create Image Animation in visual Basic


Creating Image Animation
One way to create image animation is to use a picture box and keep changing its Picture property to display successive frames of an animation. You can store the images themselves in the program, such as using an image list control or an array of Picture objects. We’ve seen how to create animation earlier in this book in our chapter on Visual Basic timers using image lists; here, we can do the same thing using an array of Picture objects.
We add a timer control, Timer1, to the program and set its Interval property to 1000 (the Interval property is measured in milliseconds, 1/1000s of a second), which means the Timer1_Timer() event handler will be called once a second. We also add a picture box, Picture1, in which to display images and a command button, Command1, with the caption “Start animation” to start the animation.For the purposes of this example, we will just switch back and forth between two images in the picture box. These two images are the two images in the Picture object array, picObjects, which we store in the form’s
(General) section:
Dim picObjects(1 To 2) As Picture
We load those images when the form first loads:
Private Sub Form_Load()
Set picObjects(1) = LoadPicture("c:\vbbb\pictureanimation\image1.bmp")
Set picObjects(2) = LoadPicture("c:\vbbb\pictureanimation\image2.bmp")
End Sub
To switch back and forth, we use a static Boolean flag named blnImage1 like this, alternating between images
in the Picture object array in Timer1_Timer:
Private Sub Timer1_Timer()
Static blnImage1 As Boolean
If blnImage1 Then
Picture1.Picture = picObjects(1)
Else
Picture1.Picture = picObjects(2)
End If

At the end of Timer1_Timer, we toggle the blnImage1 flag this way:
Private Sub Timer1_Timer()
Static blnImage1 As Boolean
If blnImage1 Then
Picture1.Picture = picObjects(1)
Else
Picture1.Picture = picObjects(2)
End If
blnImage1 = Not blnImage1
End Sub

All that’s left is to start the animation when the user clicks the command button, and we do that like this, by 
enabling the timer:



Private Sub Command1_Click()
Timer1.Enabled = True
End Sub
And that’s all we need—now we’re supporting animation using picture boxes and Picture object arrays.

 
Twitter Bird Gadget