Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
Application Class
 DoEvents Method

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
Application..::.DoEvents Method

Processes all Windows messages currently in the message queue.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)
Visual Basic (Declaration)
Public Shared Sub DoEvents
Visual Basic (Usage)
Application.DoEvents()
C#
public static void DoEvents()
Visual C++
public:
static void DoEvents()
JScript
public static function DoEvents()

When you run a Windows Form, it creates the new form, which then waits for events to handle. Each time the form handles an event, it processes all the code associated with that event. All other events wait in the queue. While your code handles the event, your application does not respond. For example, the window does not repaint if another window is dragged on top.

If you call DoEvents in your code, your application can handle the other events. For example, if you have a form that adds data to a ListBox and add DoEvents to your code, your form repaints when another window is dragged over it. If you remove DoEvents from your code, your form will not repaint until the click event handler of the button is finished executing. For more information on messaging, see User Input in Windows Forms.

Unlike Visual Basic 6.0, the DoEvents method does not call the Thread..::.Sleep method.

Typically, you use this method in a loop to process messages.

Caution noteCaution:

Calling this method can cause code to be re-entered if a message raises an event.

The following code example demonstrates using the DoEvents method. When the example runs, a user can select graphics files from an OpenFileDialog. The selected files are displayed in the form. The DoEvents method forces a repaint of the form for each graphics file opened. To run this example, paste the following code in a form containing a PictureBox named PictureBox1, an OpenFileDialog named OpenFileDialog1, and a button named fileButton. Call the InitializePictureBox and InitializeOpenFileDialog methods from the form's constructor or Load method.

NoteNote:

In Visual Studio, if you add an OpenFileDialog to your form by using a drag operation, you will have to modify the following InitializeOpenFileDialog method by removing the line that creates a new instance of OpenFileDialog.

The example also requires that the Control..::.Click event of the Button control and the FileOk event of the OpenFileDialog are connected to the event handlers defined in the example. When the example is running, display the dialog box by clicking the button.

Visual Basic
Private Sub InitializePictureBox()
    Me.PictureBox1 = New System.Windows.Forms.PictureBox
    Me.PictureBox1.BorderStyle = _
        System.Windows.Forms.BorderStyle.FixedSingle
    Me.PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
    Me.PictureBox1.Location = New System.Drawing.Point(72, 112)
    Me.PictureBox1.Name = "PictureBox1"
    Me.PictureBox1.Size = New System.Drawing.Size(160, 136)
    Me.PictureBox1.TabStop = False
End Sub

Private Sub InitializeOpenFileDialog()
    Me.OpenFileDialog1 = New System.Windows.Forms.OpenFileDialog

    ' Set the file dialog to filter for graphics files.
    Me.OpenFileDialog1.Filter = _
    "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"

    ' Allow the user to select multiple images.
    Me.OpenFileDialog1.Multiselect = True
    Me.OpenFileDialog1.Title = "My Image Browser"
End Sub

Private Sub fileButton_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles FileButton.Click
    OpenFileDialog1.ShowDialog()
End Sub


' This method handles the FileOK event.  It opens each file 
' selected and loads the image from a stream into PictureBox1.
Private Sub OpenFileDialog1_FileOk(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
 Handles OpenFileDialog1.FileOk

    Me.Activate()
    Dim file, files() As String
    files = OpenFileDialog1.FileNames

    ' Open each file and display the image in PictureBox1.
    ' Call Application.DoEvents to force a repaint after each
    ' file is read.        
    For Each file In files
        Dim fileInfo As System.IO.FileInfo = New System.IO.FileInfo(file)
        Dim fileStream As System.IO.FileStream = fileInfo.OpenRead()
        PictureBox1.Image = System.Drawing.Image.FromStream(fileStream)
        Application.DoEvents()
        fileStream.Close()

        ' Call Sleep so the picture is briefly displayed, 
        'which will create a slide-show effect.
        System.Threading.Thread.Sleep(2000)
    Next
    PictureBox1.Image = Nothing
End Sub


C#
    private void InitializePictureBox()
    {
        this.pictureBox1 = new System.Windows.Forms.PictureBox();
        this.pictureBox1.BorderStyle = 
            System.Windows.Forms.BorderStyle.FixedSingle;
        this.pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
        this.pictureBox1.Location = new System.Drawing.Point(72, 112);
        this.pictureBox1.Name = "pictureBox1";
        this.pictureBox1.Size = new System.Drawing.Size(160, 136);
        this.pictureBox1.TabIndex = 6;
        this.pictureBox1.TabStop = false;
    }

    private void InitializeOpenFileDialog()
    {
        this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();

        // Set the file dialog to filter for graphics files.
        this.openFileDialog1.Filter = 
            "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" + 
            "All files (*.*)|*.*";

        // Allow the user to select multiple images.
        this.openFileDialog1.Multiselect = true;
        this.openFileDialog1.Title = "My Image Browser";
        
    }

    private void fileButton_Click(System.Object sender, System.EventArgs e)
    {
        openFileDialog1.ShowDialog();
    }


    // This method handles the FileOK event.  It opens each file 
    // selected and loads the image from a stream into pictureBox1.
    private void openFileDialog1_FileOk(object sender, 
        System.ComponentModel.CancelEventArgs e)
    {

        this.Activate();
         string[] files = openFileDialog1.FileNames;

        // Open each file and display the image in pictureBox1.
        // Call Application.DoEvents to force a repaint after each
        // file is read.        
        foreach (string file in files )
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(file);
            System.IO.FileStream fileStream = fileInfo.OpenRead();
            pictureBox1.Image = System.Drawing.Image.FromStream(fileStream);
            Application.DoEvents();
            fileStream.Close();

            // Call Sleep so the picture is briefly displayed, 
            //which will create a slide-show effect.
            System.Threading.Thread.Sleep(2000);
        }
        pictureBox1.Image = null;
    }

Visual C++
void InitializePictureBox()
{
   this->PictureBox1 = gcnew System::Windows::Forms::PictureBox;
   this->PictureBox1->BorderStyle =
      System::Windows::Forms::BorderStyle::FixedSingle;
   this->PictureBox1->SizeMode = PictureBoxSizeMode::StretchImage;
   this->PictureBox1->Location = System::Drawing::Point( 72, 112 );
   this->PictureBox1->Name = "PictureBox1";
   this->PictureBox1->Size = System::Drawing::Size( 160, 136 );
   this->PictureBox1->TabIndex = 6;
   this->PictureBox1->TabStop = false;
}

void InitializeOpenFileDialog()
{
   this->OpenFileDialog1 = gcnew System::Windows::Forms::OpenFileDialog;

   // Set the file dialog to filter for graphics files.
   this->OpenFileDialog1->Filter =
      "Images (*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|" +
      "All files (*.*)|*.*";

   // Allow the user to select multiple images.
   this->OpenFileDialog1->Multiselect = true;
   this->OpenFileDialog1->Title = "My Image Browser";
}

void fileButton_Click( System::Object^ sender, System::EventArgs^ e )
{
   OpenFileDialog1->ShowDialog();
}

// This method handles the FileOK event.  It opens each file 
// selected and loads the image from a stream into PictureBox1.
void OpenFileDialog1_FileOk( Object^ sender,
   System::ComponentModel::CancelEventArgs^ e )
{
   this->Activate();
   array<String^>^ files = OpenFileDialog1->FileNames;

   // Open each file and display the image in PictureBox1.
   // Call Application.DoEvents to force a repaint after each
   // file is read.        
   for each ( String^ file in files )
   {
      System::IO::FileInfo^ fileInfo = gcnew System::IO::FileInfo( file );
      System::IO::FileStream^ fileStream = fileInfo->OpenRead();
      PictureBox1->Image = System::Drawing::Image::FromStream( fileStream );
      Application::DoEvents();
      fileStream->Close();

      // Call Sleep so the picture is briefly displayed, 
      //which will create a slide-show effect.
      System::Threading::Thread::Sleep( 2000 );
   }
   PictureBox1->Image = nullptr;
}

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Application.DoEvents is potentially dangerous      Ifeanyi Echeruo [MSFT] ... Thomas Lee   |   Edit   |   Show History

Application.DoEvents is potentially dangerous and can lead to unstable code. Take a look at http://blogs.msdn.com/jfoscoding/archive/2005/08/06/448560.aspx for an explanation and possibly safer methods for replacing Application.DoEvents

It is dangerous!      ovianao0000000   |   Edit   |   Show History
> I'm handling a buttonclick that parses through ~ 1000 records and adds them to a listview control, before it comes out again (takes about 3 seconds).

> If I add Application.DoEvents right before adding the records into my listview control (for a window refresh), and the user clicks the button again (within 3 seconds), I get twice as many records in my listview control. The code re-entered and just kept adding them to the same listview reference. I was astonished! I knew what was causing it, but I wasn't sure why.

> It was all happening on the same thread (obviously), but just in case, I tested to make sure. First thing that came to mind was "an interrupt is happening somewhere"; almost like an event handler is interrupting this event handler while it's running. Thanks for the above article [http://blogs.msdn.com/jfoscoding/archive/2005/08/06/448560.aspx] I was curious, but now I understand completely. Away with Application.DoEvents!!!
Application.DoEvents invites Re-entrancy      xalnix   |   Edit   |   Show History

The documentation has the warning... "Calling this method can cause code to be re-entered if a message raises an event." The fact is, if you call this method as an indirect result of a user gesture (mouse click, key stroke, etc.), and the user's gesture does not complete within three seconds, the user will repeat the keystroke or mouse-click. So re-entrancy is nearly guaranteed. If you use this method, then program for re-entrancy because any tester worth his salt will try to make the code blow-up on re-entrancy (the standard "happy-click" test). To use this method, one must understand re-entrancy, what it is, how it hurts, and how to avoid it. Better would be to switch to a more robust coding practice and avoid "DoEvents" altogether.

Use (your control).Update() instead!      ToolmakerSteve ... Thomas Lee   |   Edit   |   Show History
The reason given in this doc page for using Application.DoEvents (to allow your form to re-paint) is a TERRIBLE reason. Don't do it! Instead, call the Update() method on your control or your form, if all you need is a re-paint:
Me.Update()
-or-
Me.ParentForm.Update()


This method should be deprcated      btudor   |   Edit   |   Show History
There is never a reason to call this method, and every reason not to. It should be marked "deprecated" and eventually removed from the framework. See comments of others. The sample is a terrible example of coding practices. If the DoEvents() method processes WM_QUIT, your application will quit in the middle of your processing. There are many suitable alternatives, depending on the situation.

Use Control.Update(), use background worker, call methods asynchronously through a delegae, queue up a task on the thread pool; even creating a thread and running the work on the threadproc is better than making this call.
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker