Search code examples
c#winformswindows-servicessetup-project

Windows form not responding: How can I resolve this issue?


I create a windows service and a setup project.

During the installation of the windows service, I add a windows form which allow the user to upload a file in the project folder but when I click on the button to upload the file my windows form is always on state not responding

not responding

ProjectInstaller of my windows service

public override void Install(IDictionary stateSaver)
{
    base.Install(stateSaver);

    Form1 validationForm = new Form1();
    validationForm.ShowDialog();
}

Windows form

public Form1()
{
    InitializeComponent();
}

private void button1_Click_1(object sender, EventArgs e)
{
    try
    {
        OpenFileDialog fileDialog = new OpenFileDialog();
        //fileDialog.Filter = "Dat files |*.dat";
        fileDialog.Multiselect = false;

        if (fileDialog.ShowDialog() == DialogResult.OK)
        {
            var path = fileDialog.FileName;
            Process.Start(path);
        }
    }
    catch (Exception)
    {
        MessageBox.Show("An error occured", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Solution

  • Try this.

    private void button1_Click(object sender, EventArgs e)
    {
        var task = new Thread(() => GetFile());
        task.SetApartmentState(ApartmentState.STA);
        task.Start();
        task.Join();
    }
    
    private static void GetFile()
    {
        try
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            //fileDialog.Filter = "Dat files |*.dat";
            fileDialog.Multiselect = false;
    
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                var path = fileDialog.FileName;
                Process.Start(path);
            }
        }
        catch (Exception)
        {
            MessageBox.Show("An error occured", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }