Search code examples
c#excelvstoadd-in

OpenFileDialog doesn't work when in an Excel Add-In?


I've got an OpenFileDialog in a Windows Form which runs absolutely fine, howevever, when I want to do the same within an Excel Add-In, it does not seem to do anything. Below is an extract of my code, however I am struggling to see where the issue is as the code is identical for both (text box, openFileDialog and button names are identical).

public partial class DashboardControl : UserControl
{
    public DashboardControl()
    {
        InitializeComponent();
    }

    private void DashboardControl_Load(object sender, EventArgs e)
    {

    }

    private void fileLocationText_TextChanged(object sender, EventArgs e)
    {

    }


    private void openFile_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();

    }

    private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
    {
        fileLocationText.Text = openFileDialog1.FileName;
    }
}

Solution

  • Looks like the dialog is shown behind the Excel window. You need to set a parent window hanlde for the dialog ro bring it to the front. See SetForegroundWindow functin which brings the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window, and various visual cues are changed for the user. The system assigns a slightly higher priority to the thread that created the foreground window than it does to other threads.

    Note, the Show and ShowDialog methods of the System.Windows.Forms.Form class accepts an instance of the IWin32Window interface which allows to specify the parent window handle.