Search code examples
c#winformsesri

Force dialog close in C#


I'm writing a GIS application in C#. A portion of the application allows the user to select a KML file, and then the program will process that file. I'm using an OpenFileDialog, but the problem is that all of the code is executed before the dialog gets closed (and after the user has OK'd the file). It takes quite awhile because the program has to zoom and do other things. Is there a way to close the dialog programmatically before my code is executed?

EDIT: Some code for those who ask.

private void OnKMLFileSet(object sender, CancelEventArgs e)
{
    Polygon polygon = KmlToPolygon(openFileDialog2.FileName);
    // After this, I no longer need the file, but the dialog stays open until the end of the method
    Graphic graphic = new Graphic();
    graphic.Geometry = polygon;
    textBox1.Text = string.Format("{0:n}", CalculateAreaInSqKilometers(polygon)).Split('.')[0];
    textBox2.Text = string.Format("{0:n}", CalculateAreaInSqMiles(polygon)).Split('.')[0];
    textBox3.Text = string.Format("{0:n}", CalculateAreaInSqKnots(polygon)).Split('.')[0];
    Note polyInfo = new Note("Polygon with nautical area: " + textBox3.Text, polygon);
    map.Map.ChildItems.Add(polyInfo);
    map.ZoomTo(polygon.GetEnvelope());
}

Solution

  • It sounds like the dialog is actually closed, but it's still "visible" because the main window is busy and hasn't repainted itself yet.

    Some ideas:

    • The easy way: call the Refresh() method on the main form where the dialog is still visible. Always call it immediately after ShowDialog returns.
    • If loading takes quite a bit of time, it might be desirable to create a pop-up "loading" dialog, possibly with a cancel button. Use the BackgroundWorker class to load the file in a background thread. When the worker is done, the file is loaded and the pop-up window can be closed. Remember not to change anything in the user interface from the background thread without proper synchronization.

    EDIT: After looking at the code, I think I see your problem. You're handling the FileOk event. This will have the effect you are trying to avoid. Use the dialog like this:

    if (openFileDialog1.ShowDialog() == DialogResult.OK) {
        // open file
    }
    

    Don't use the FileOk event. I've never had reason to use it before... Also it might be helpful to follow the advice I already gave.