K & K Consulting    K & K Consulting

K&K Home VB Guru Home Search VB Site VB Code VB Tips VB Tutorials VB Questions

K&K Home
Up

 

Answered Questions For July 2000


Verify Windows Password

From:  Mohammed Mrini
Date:  July 24,2000

How can I verify if the password entered by a user in my application matches their network password? (I am able to display their username by using GetUserName). Thanks

The Guru's Response:

Sorry Mohammed,  I have looked every ware and can not find an API call that will do this. Sorry =(  If anyone knows how to do this, please email me and I will post it here.

Scrollable Forms

From:  Alex Koshansky
Date:  July 24,2000

The form I am designing is too big to fit on screen. Is there any way to make it scrollable? It is illegal (in my case) to break it on pages. 

Thanks.

The Guru's Response:

Yes, there is a way to make it scrollable. Naturally, you will need add to add your horizontal and vertical bar to your form.  Then you will need to create a function that will move your controls around the form to reflect the amount scrolled, even to the point of scrolling them off the form.  You will add or subtract from the Top & Left Properties to do this.  I have got you started here with the Horizontal scrolling, just create a similar one for your Vertical scroll and you are all set.  Note:  in the scroll function I have had it skip moving the scroll bars itself, you do not want them to move them LOL.

Option Explicit

Dim HAmount As Long

Private Enum ScrollType
  Plus = 0
  Minus = 1
End Enum

Private Sub ScrollH(ByVal Amount As Integer, HowToScroll As ScrollType)

Dim ctl As Control

For Each ctl In Me.Controls
   If Not (ctl.Name = "HScroll1") And (Not ctl.Name = "VScroll1") Then
      If HowToScroll = Plus Then
         ctl.Left = ctl.Left + Amount
      Else
         ctl.Left = ctl.Left - Amount
      End If
   End If
Next

End Sub

Private Sub Form_Load()
   HAmount = 0
End Sub

Private Sub HScroll1_Change()
   If HScroll1.Value > HAmount Then
      ScrollH HScroll1.Value - HAmount, Plus
   Else
      ScrollH HAmount - HScroll1.Value, Minus
   End If

   HAmount = HScroll1.Value

End Sub

Private Sub HScroll1_Scroll()

   If HScroll1.Value > HAmount Then
      ScrollH HScroll1.Value - HAmount, Plus
   Else
      ScrollH HAmount - HScroll1.Value, Minus
   End If

   HAmount = HScroll1.Value

End Sub

I hope this helps

File Functions

From:  David Lane
Date:  July 19,2000

Hi, 

I only just begun progarmming in Visual Basic and I have got stuck on a project I have been set at Work. How do call the commmand prompt from within a Vb program so that you can, for example rename a file (e.g. c:\rename text.text newtext)?

The Guru's Response:

To call the Command Prompt, or as some call it, The DOS Box, you would use the Shell() Function. This runs an executable program and returns a Variant (Double) representing the program's task ID if successful, otherwise it returns zero. The Function Prototype is as follows:

Shell(pathname[,windowstyle])

The Windowstyle argument is an Optional  Variant (Integer) corresponding to the style of the window in which the program is to be run. If windowstyle is omitted, the program is started minimized with focus.

The only problem with the Shell Function is, it is used only to Start an other application, once it is started, you can not interact with it; I know this is not what you want.  You also want to rename files ect, so if all you want is a Command Prompt so you can run file commands, you can do this right from VB, with the help of some built in VB functions, I have listed them as follows:

Function Name

Description

Prototype

Name Renames a disk file, directory, or folder. Name oldpathname As newpathname
ChDir Changes the current or default directory on a specified drive ChDir(Path As String)
CurDir Returns the current path CurDir([Drive]) As String
Dir Returns a String representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive. Function Dir([PathName], [Attributes As VbFileAttribute = vbNormal]) As String
CopyFile Copies a file FileCopy(Source As String, Destination As String)
FileDateTime Returns the date and time stamp of a file FileDateTime(PathName As String)
FileLen Returns the length of a file in bytes FileLen(PathName As String) As Long
Kill Deletes files from a disk Kill(PathName)
MkDir Creates a new directory or folder MkDir(Path As String)
RmDir Removes an existing directory or folder RmDir(Path As String)

I hope this helps

SQL Expert 1

Update To Rounding Numbers Question 

Date:  July 17,2000

Gino De Buono, MCSD, MCP, MCP+ I, MCSE+ I, MCDBA, wrote:

About your answer to Andrew about rounding numbers Round(Num,AfterDecNums) this command actually has a major bug - Try it 
If you Round(2.5,0) -> 2 and Round(3.5,0) -> 4 all even numbers and a point 5 will round down and all odd numbers round up. A lot a C/C++ programmers use this inability of VB to round properly as a source of much hissing of the inferior users of VB. 

Any way just to let you know - Its one of those VB features.

The Guru's Response:

Thanks for letting us know Gino.  The interesting thing is, the VB runtime, that has all the VB Function Calls in it, is written in C(++).  Well Andrew, I hope you read this before putting the Round() Function in your code, that could be a bug that would be hard to track down.  Because you only need to return whole numbers, I have wiped up a quick and dirty function for you.  If you really needed the full functionality of the Round() function, it would not take too long to modify it.

Public Function MyRound(ByVal MyNumberToRound As Double) As Integer

   MyRound = Int(MyNumberToRound + 0.5)

End Function

Rounding Numbers

From:  Andrew Weller
Date:  July 15,2000

I have made up a calculator modial but my answer needs to be a round number example if calculator answer = 4.6 it needs to be rounded of to the next full number 5.0 can you help?

The Guru's Response:

To round any number, Integer, Single or Double, you use the Round() function. The Function Prototype is as follows:

Round(expression[, numdecimalplaces])

The numdecimalplaces is Optional. It is the Number indicating how many places to the right of the decimal are included in the rounding. If omitted, integers are returned by the Round function.

I hope this helps

Print Data Reports in Landscape

From:  Nikos Miaoulis
Date:  July 11,2000

Is it possible to have a data report on a project but the data are printed in landscape? do i need to use API ? please help!

The Guru's Response:

You can set up the Form size to look like it is in Landscape using the DataReport properties, but when you click the print button on the top left corner, it will bring up your printing properties, just select Landscape in the orientation section of the Page Setup Tab. 

I hope this helps

Update To Form Display Question 

Date:  July 11,2000

Hi 

I've tried what you've suggested (to get one from to display another from), but it doesn't seem to work. 

My main form has a command button called Viewing, when I click on this it should display the viewing form 

My Viewing Form is called ViewingForm as is saved as VIEWING.FRM. 

I've tried: 

Public Sub cmdViewing_Click() ViewingForm.Show 

Doesn't work, i've tried quite a few other ways, but I cannot seem to get it to work. Can you help again thanks

The Guru's Response:

Hmmmmmmm..........It has been a about 2 years since I worked with VB5, but I was sure you could just use the show method.  Let's try the longer way:

Public Sub cmdViewing_Click()

   Load ViewingForm
   ViewingForm.Show

End Sub

Ok, now, in the chance that this will not work for you, there is one more way to do it:

Public Sub cmdViewing_Click()

   Dim ViewingForm2 as ViewingForm

   set ViewingForm2 = new ViewingForm

   ViewingForm2.Show

End Sub

If both of these do not work, then there may to be a problem with your system/Set Up.  Do you have the most up-to-date service pack for your VB5 and/or OS?  Visual Studio 97 went up to SP3, NT is up to SP 6.  If these are up-to-date, check the MSDN Online for any knowledgebase entries. 

I hope this helps

WinFax?

From:  Philip Goode
Date:  July 11,2000

I am trying to produce faxes from an ACCESS database automatically. Currently I produce a report from a query and then use a module to do the clever stuff. Using Winfax PRO v.10's SDK, I can extract the fax number from a single page report and send a fax cover to it. Two problems exist :- 

1) where the report produces a number of pages, I need to pick out more than one fax number (one per page). I can't see a way of doing this from the report so I have been trying to write some code which looks at the query directly and passes the value of the fax number fields to a parameter which can then be passed to Winfax. So far, despite reading lots of books, I have yet to find a way of performing this simple task using V.B. I have managed to do some fairly complicated stuff with the datbase using VB but I must be missing something obvious with regard to this one. 

2) Any suggestions on how I would pass the actual relevant page of the report to WINFAX. Winfax needs the page saved as a file (attachment) for my procedure to work automatically. Alternatively, Do you think I can read the fields in the database and then output them to a WORD mailmerge document. I reckon this would work but I still need to know how to read a field and output its value to a parameter. 

Please excuse me if the answers to my questions are obvious or indeed my questions are daft, but despite being OK on ACCESS and DBASE etc V.B is still a bit of a mystery to me. Last time I did any serious development work it was in CLIPPER - I trust that VB is a lot better than that !!! 

Thank you in advance for your time and I will be very grateful for any help you may offer. 

Philip Goode. 

The Guru's Response:

Well I have good news & bad news,  The good news is I can help you with the first point, the bad news is I have not worked with Winfax before so I can not help you with that =(.  Anyhow, here is how you would "cycle" through a database recordset and pass the fax number to your Winfax API :

Public Sub DoWinFaxStuff()

   Dim FaxNum As String
   Dim SQL As String
   Dim MyRS As ADODB.Recordset

   Set MyRS = New ADODB.Recordset

   SQL = "Select FaxNumber from <Your Database Name>;"

   With MyRS 'See the Word O' The month for May to see more on the with Statement

      .CursorLocation = adUseClient
      .CursorType = adOpenStatic
      .Open SQL, "<Your DSN or connection to your Access Database>"
      .ActiveConnection = Nothing ' We got the data so we do not have to stay connected.

      Do While Not .EOF
         DoEvents

         FaxNum = !FaxNumber ' set Faxnum to the FaxNumber value in the database

         '*********************************************
         '* Code for passing FaxNum to the Winfax API*
         '*********************************************

         If Not .EOF Then .MoveNext
      Loop

   End With

End Sub

I hope this helps

Form Display

From:  RAHEENA QAIYUM
Date:  July 10,2000

Hi

I'm in the process of developing a database (the database is for an Estate Agent) using visual basic 5. However, the problem I am incurring is with regard to linking. On my form I have the following command buttons: property, viewing, landlord, client, sales etc. What I want to do is that if I click on the viewing command button this will bring/display the viewing form or if I click on clients command the client screen will display, allowing me to update, add or retrieve information How do I do this?

Also, I have a problem with regard to search. I have a command button called find - this allows me to search for records. If I type the surname of a client it brings up the details of the person specified. However, I would like to search for a property or client by specifying Property ID or Client ID. The ID consists of words and numbers. Again how do I do this.

I have little experience in visual basic 5 and I am still in the process of learning. I would be grateful if you could assist me with regard to these issues

thank you

raheena

The Guru's Response:

To get one form to display another form, you use the Show property of the form.  For example, if your viewing form is called frmView, then use the following code in your main form:

Public Sub Command_Click ()

   frmView.Show

End Sub

In regards to your searching problem, create a new Search form and place some Option Buttons on it, one for each of the fields you want to search on.  Then place a TextBox on the form so the user can enter the PropertyID or ClientID etc, last but not least, add a Command button called cmdSearch.  You can then add this code to the search form:

Option Explicit

Dim SearchField As String    ' Form Level Variable

Private Sub cmdSearch_Click()

   Dim SQL As String

   SQL = "Select * from <Your Database Name> Where " & SearchField & " = ' " &  txtSearch.Text & " ' "

   ' Note the single quote before and after the txtsearch, you need this to pass non-numeric data to the database.
   ' Your Code to send the new SQL string to your database for re-query

End Sub

Private Sub optSearchField_Click(Index As Integer)

   Select Case Index
      Case Is = 0
         SearchField = " Surname "
      Case Is = 1
         SearchField = " PropertyID "
      Case Is = 2
         SearchField = " ClientID "
   End Select

End Sub

I Hope this helps

GIF Files & VB

From:  Kanin Kalra
Date:  July 10,2000

How to save any picture file to a transparent Gif file format using VB6 ?

The Guru's Response:

Interesting question, I have thumbed through a few of my usual resources and came up with a bit fat 0. This seem to be a bit confusing; the GIF format  was originally designed by CompuServe. Up to a few years ago, CompuServe was trying to get any one with even one GIF on there site to pay a $10,000 licensing fee. Visual Basic 5 documentation listed that you could use a GIF in the PictureBox, but you may have to be licensed to use it.  I have searched all the online and CD based MSDN files and that stipulation is no longer there.  So, this the bottom line:  I have not found a way to natively (through code) convert one file format to another, BUT, you may be able to attach to an API of another Application to do it.  BUT, you may or may not need to pay a licensing fee to do this.  So, as you can see, it is a bit confusing.  Sorry I could not be of more help.

Why not create a bulletin board?

From:  PKM_HercZ
Date:  July 07,2000

Hey Guru, I was looking at your archive questions, and you have lots of them already. Great job!!! I was wandering wouldn't it be easier for you to just make a buletin board? Like our tactical forum (www.ezboard.com)? That way ppl can post their reply and stuff. Just my suggestion, Herc

The Guru's Response:

Hey Herc,

For those of you that have not noticed, Herc is a regular contributor (question asker) here on the "Ask The Guru" page.  He had the very first question posted,  He is also my clan mate in the Unreal/Unreal Tournament clan, PKM, short for Pokemon. But most importantly, he is an aspiring VB developer.

Anyway,  I did think of doing that (creating a bulletin board), but I wanted to create more of a personal feeling here, I enjoy answering the questions, and I hope I can teach you something, not just give you the answer. (the teach you to fish thing).  I think all of that would be lost in a bulletin board.  Thanks for the suggestion, and Frag you later.

Telnet???

From:  Jason Carney
Date:  July 07,2000

How do you go about creating a telnet client which can use any telnet service through Winsock?

The Guru's Response:

Sorry, I can't help you at all with this one, I do not know even where to point you in the right direction.

Roll your own files

From:  Brian Haley
Date:  July 07,2000

Hi. Do you know how to put several files into a single file, somewhat like winzip does, and then extract them out? Thanks

The Guru's Response:

I thought about this for a bit and came up with an interesting idea, Access will allow you to use an OLE Object data type.  This data type will let you store an object (such as a Microsoft Excel spreadsheet, a Microsoft Word document, graphics, sounds, or other binary data) linked to or embedded in a Microsoft Access table.  Now, you can create an Access Database in code within VB, the cool thing is, you do not even have to call it an mdb file, call it anything you want.  Then just load your file(s) into the OLE Object field.  Remember, you can install and use an Access database on anyone's computer, even if they do not have Office or Access installed, VB gives you right to do this royalty free.

VB & Outlook

From:  Ramon Morales
Date:  July 07,2000

I am to get VB to delete an attachment in Outlook. Following the examples in the help file, I can get to the attachement without problem. I can even give the command to remove the attachment without error. But it doesn't remove! So I'm stuck. I want to remove attachments based on some criteria (like find all instances of "old.doc" and delete). 

Here's the code so far: Dim StartDate As Date Dim MailItem As Object Dim sSubject As String Dim iAttachmentCount As Integer Dim calItems As Object Dim filtItems As Object Dim iMailCount As Integer Dim iLoop As Integer Dim iSubLoop As Integer Dim xyz As Object Dim abc As Object Dim s As String 

On Error GoTo StandardError 

Set oOutApp = CreateObject("Outlook.Application") Set MailFolder = oOutApp.GetNamespace("MAPI").GetDefaultFolder(6) 'olFolderInbox 

iMailCount = MailFolder.Items.Count 

For iLoop = 1 To iMailCount 

iAttachmentCount = MailFolder.Items.Item(iLoop).Attachments.Count If iAttachmentCount > 0 Then 

Set MailItem = MailFolder.Items.Item(iLoop).Attachments Set xyz = MailFolder.Items Set abc = xyz(iLoop).Attachments While abc.Count > 0 abc.Remove 1 'This part doesn't work Wend end if next iloop 

Any ideas on what I'm doing wrong? 

The Guru's Response:

I am sorry, I have not done too much work with VB & Outlook, just some simple outgoing mail.  I played with your code for a bit, but was having the same problems as you.  If anyone knows why this code is not working, email me and I will post it here.

Access 97 & ADO

From:  Bill Wolf
Date:  July 07,2000

I have an Access 97 Table consisting of two colums: PayCodeID, numbers 1 through 14....and PayCode, which is text e.g. REG, VOL, BV, etc...using ADO I have been trying to use a "DataCombo Box" to list the numbers, and have the corresponding text show up in a "TextBox" eg. Selct the number 1 in the datacombo, and REG appears in the textbox. I'm using VB6 Pro...and have been unable to make this work!!! YES, you may have guessed, I'm new to VB6 programming...but what to me should be so simple using ADO,has become a nightmare and a quest for answers...PLEASE HELP! Thank you, 

Bill Wolf

The Guru's Response:

It may not be pretty, but this will do the trick.  Place this code in your dbcombobox Click Event:

MyRS.AbsolutePosition = CLng(dbCombo1.Text)

So every time you change the number in the ComboBox, it will change the record pointer to that record, and show the appropriate text.

The AbsolutePosition indicates the ordinal position of a Recordset object's current record. It Sets or returns a Long value from 1 to the number of records in the Recordset object (RecordCount), or returns one of the PositionEnum values. Use the AbsolutePosition property to move to a record based on its ordinal position in the Recordset object, or to determine the ordinal position of the current record.  I usually use AbsolutePosition to retrieve the record position, but in this case, setting it will do the job.

ActiveX DLL's

From:  Simon Smulovitch
Date:  July 04,2000

If I have written a dll using VB6.... how comes when I try and access one of the public functions in it using a CGI, I get the error "entry point not found in dll"? 

Many thanks

The Guru's Response:

There are two types of DLL's that can be used in a Win32 system

bullet A Standard DLL: This is a collection of functions that are Exportable to other programs, any Win32 application can load the DLL and call these public functions.  A DLL is usually created so different applications can share the same code, for example, shared code for Microsoft Office, this reduces code bloat and makes bug corrections easier. Another reason for this type of DLL is to expose functionality for unrelated applications in the form of an API.
bullet An ActiveX DLL: Although this type of DLL is also used to share code, it is not just a collection of functions, it is designed to be a class server.  To gain access to functions and subs, you must create a variable reference to a class within the DLL. For example RS.MoveNext, MoveNext is a sub within the RS (ADODB.Recordset)class. This type of DLL is also known as a COM/DCOM  DLL, depending on where the DLL is located in reference to the client application (COM if it is local, DCOM if it is sitting on a network somewhere). 

As of version 6, Visual Basic can only create the ActiveX/COM type of DLL, where as C or C++ can create both.  In order for you to be able to use an ActiveX DLL, your application MUST BE COM compliant or at least COM aware.  So, herein lies your problem, you are trying to create a standard DLL from an ActiveX DLL, and/or I would bet dollars to donuts that the CGI is not COM compliant and is trying to load your DLL as a standard DLL.

MDIForms

From:  Les Quines
Date:  July 03,2000

We're working on a database frontend using an MDI with child forms for vendors, customers etc. Presently we use the menuitems and toolbar to navigate through the records. I would like to be able to use the keyboard also, such as pagedown to move to previous record. The MDI form does not have a keydown event. How can I do this?

The Guru's Response:

One form in the MDI Form always has focus, so if you put code in all of the child forms' KeyDown event, you can do exactly what you need. For example: paste in the following code in any/all of your Child forms:

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)

Select Case KeyCode
  Case vbKeyEscape
     cmdClose_Click
  Case vbKeyEnd
     cmdLast_Click
  Case vbKeyHome
     cmdFirst_Click
  Case vbKeyUp, vbKeyPageUp
    If Shift = vbCtrlMask Then
       cmdFirst_Click
    Else
       cmdPrevious_Click
    End If
  Case vbKeyDown, vbKeyPageDown
    If Shift = vbCtrlMask Then
       cmdLast_Click
    Else
       cmdNext_Click
    End If
End Select

End Sub

Just make sure you put code behind the command buttons or what ever to move the recordset forward or back.

Data Binding & VB 6

From:  Gerard Carignan
Date:  July 03,2000

Hello. I am new at programming, and I am trying to create a program that searches an Access database, at run-time. I want to have a form that lets a person run a query on all fields, by typing one or more words (e.g.: "Toyota AND Trucks"). Another possibility is to have a form with multiple text boxes, with each representing a specific type of info (such as: telephone number, first and last name, street address, etc). When someone types in the correct info in one field and submits, related info shows up in the other fields. 

I'd appreciate some direction in this matter. Either a tutorial, or the name of a good, explicit book that covers this topic. 

Thank You, 

Jerry

The Guru's Response:

This is a toughie, not that the solution is hard, but more in how I will guide you in the right direction in a short amount of space/time.  Basically you will want to do some form of Data Binding, most controls like the Textbox, Label, ComboBox ect, have three properties that you are interested in, DataSource, DataMember and DataField.  The DataSource creates the connection to the database and can be one of three objects:

  1. A DataControl 
  2. A DataSource Class
  3. A DataEnvironment

The DataMember is the recordset that you want to bind to, the Class or DE can have more then one recordset.

The DataField is the actual database field you want the textbox or whatever to show.  You can use the various events, for example, Change(),Validate(),Keypress(), lostFocus() ect, to trap when the user selects Toyota or whatever, and pass a new SQL statement to the DataMember, this will then cascade the new data to other controls bound to that DataMember.

As a beginner to VB, I would recommend Mastering Microsoft Visual Basic 6.0 Fundamentals this will guide you in getting started in VB and Data Access with data binding ect.

From there, I always recommend Mastering Microsoft Visual Basic 6 Development This book/CD gets more in-depth with Data Access and VB.

Winsock API

From:  CHIHI Boubaker
Date:  July 03,2000

Thank you first! I'm a VB developer from Burkina Faso. I want to develop a TCP server tha can handles about 30 clients. It 's main function is to lisen and estalish a connection then process a query from the client and then disconnect. It must be multi-threaded ! I can use the Winsock control an the multi-threaded but i would like to use the winsock api. (wsock32). 

Thank you last ! 

The Guru's Response:

I do not have a heap of experience using the Winsock control or the Winsock API, but, I can guide you in the right direction. Your choice of using the API over the control does make things easier to create a nice, neat, multi-threaded layer, that you can reuse in other applications.  Create a new ActiveX EXE project, an ActiveX EXE will create one thread per object (class), paste all the Winsock API declarations in the declarations section of the class, then add a property called PortNum and two methods, Connect() then Disconnect(). do not forget to add all of your Query code too.

Compile the EXE and add a reference to your ActiveX EXE in your main application.  Now, all you have to do is create a collection of the same type as your main ActiveX class, add 30 classes to that collection, passing the port number you want to listen on, and away you go.  You now have a fully, multi-threaded, application (31 threads, one for each class plus one for the main app).  You can ether call the disconnect method or just remove the class from the collection to stop listening to the port.

I hope this helps

A Classic Case of Thread Blocking

From:  Hensie  Van Staden
Date:  June 30,2000

Dear G,
While some routine is running for some time the forms does not respond to any messages, am I right. I want be able to stop the routine from executing when I say click a Button on the dialog box or when I hit the keyboard. The keyPress event and buttons does not respond when the routine is in the loop for obvious reasons. Is there something that I could use to force the program to execute curtain events when they occure. Or what do you do to overcome this. Thanks H Ps I'm using single Stringing or threading or what ever you call it.

The Guru's Response:

Basically, you are experiencing a classic case of thread blocking; when you enter a loop, thread execution stays in that loop, and your application will not check it's message queue for input. Not only is this frustrating for the user, because the user will think that your application has crashed, but the operating system will think your application has crashed too, because your application has not checked the message queue for an acceptable amount of time. How you prevent this is by using the VB function call, DoEvents().
DoEvents yields control to the operating system. Control is returned after the operating system has finished processing the events in its queue and all keys in the SendKeys queue have been sent.
Now, there are two ways to implement the DoEvents call, the first is as follows:

Public Sub MySub()

  Do while Myrs.EOF = False
     DoEvents
     FistName = MyRs!FirstName
     If not MyRs.EOF then MyRs.MoveNext
  Loop

End Sub

This example will work quite well for your needs, BUT, it is a terrible waste of CPU time.  The loop iterations will execute very quickly; during iteration, you keep checking the message queue & yielding thread time, defiantly over kill, plus your code will slow down considerably.  What we need is a happy balance between the two, that is where the GetInputState() API call comes in to play. The GetInputState function determines whether there are mouse-button or keyboard messages in the calling thread's message queue. If the queue contains one or more new mouse-button or keyboard messages, the return value is nonzero. If the there are no new mouse-button or keyboard messages in the queue, the return value is zero. So let's put it all together:

Paste this code into the Declaration section of a BAS file if you want the whole Application to use it, or paste into the Declaration section of your form if you want it only for that form: 

Public Declare Function GetInputState Lib "user32" Alias "GetInputState" () As Long

Next, we will re-write the last example to use the GetInputState call:

Public Sub MySub()

  Do while Myrs.EOF = False
     If GetInputState then DoEvents
     FistName = MyRs!FirstName
     If not MyRs.EOF then MyRs.MoveNext
  Loop

End Sub

This version of the code will run up to 20% faster then just using DoEvents alone.

You will now have no problem processing a  KeyPress or Button_Click event while your loop is executing. If you had a Form or Global Boolean variable called StopProcessing, you could then do the following:

Public Sub MySub()

  Do while (Myrs.EOF = False) And (StopProcessing = False)
     If GetInputState then DoEvents
     FistName = MyRs!FirstName
     If not MyRs.EOF then MyRs.MoveNext
  Loop

End Sub

Private Sub Command1_Click()
   StopProcessing = TRUE

End Sub

Note: You should also use the DoEvents call as the first line of code in a Form_Load event if you have placed any code in your Form_Initialize() event, this will help to synchronize all the events.  For example, if the system has not finished creating an object you created in the Form_Initialize event, but you try to use it in form load, you could cause an error, and this error might not happen every time.  Buy placing a DoEvents first, this will help to minimize these errors.

 

Send mail to WebMaster with questions or comments about this web site.
This website is best viewed with a screen resolution of 800*600 or better.
This website is optimized for Microsoft Internet Explorer 6.x
K&K Consulting, Proud to be a Microsoft Business Partner.
Last modified: January 31, 2002