OpenFileDialog 在 Excel 加载项中不起作用?

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

我有一个 Windows 形式的 OpenFileDialog,它运行得非常好,但是,当我想在 Excel 加载项中做同样的事情时,它似乎并没有做任何事物。下面是我的代码的摘录,但是我很难看出问题出在哪里,因为两者的代码相同(文本框、openFileDialog 和按钮名称相同)。

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;
    }
}

看起来对话框显示在 Excel window 后面。您需要为对话框设置父 window hanlde,以便将其置于最前面。请参阅 SetForegroundWindow 函数,它将创建指定 window 的线程置于前台并激活 window。键盘输入指向 window,并为用户更改各种视觉提示。系统为创建前台 window 的线程分配的优先级略高于其他线程。

注意,Show and ShowDialog methods of the System.Windows.Forms.Form class accepts an instance of the IWin32Window 接口允许指定父 window 句柄。