簡體   English   中英

C#如何在代碼中間打開FolderBrowserDialog?

[英]C# How to open a FolderBrowserDialog in the middle of the code?

我正在嘗試使用這里提到的FolderBrowserDialog

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

如果我在按下按鈕時調用Dialog,它就可以正常工作。 但是我想在代碼中間打開對話框(有一個通過套接字傳入的文件,因此在接收和保存之間,我嘗試獲取保存路徑),但是根本不會發生。

這是代碼的一部分,稱為:

 byte[] clientData = new byte[1024 * 5000];
 int receivedBytesLen = clientSocket.Receive(clientData);

 var dialog = new System.Windows.Forms.FolderBrowserDialog();
 System.Windows.Forms.DialogResult result = dialog.ShowDialog();
 string filePath = dialog.SelectedPath;

 int fileNameLen = BitConverter.ToInt32(clientData, 0);
 string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
 BinaryWriter bWrite = new BinaryWriter(File.Open(filePath + "/" + fileName, FileMode.Append)); ;
 bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
 bWrite.Close();

我應該如何打開該對話框才能正常工作?

正如其他人所述,嘗試調用UI對話框時,您很可能在單獨的線程中。

在發布的代碼中,可以將WPF方法BeginInvoke與新的Action配合使用,該Action將強制在UI線程中調用FolderBrowserDialog。

        System.Windows.Forms.DialogResult result = new DialogResult();
        string filePath = string.Empty;
        var invoking = Application.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            result = dialog.ShowDialog();
            filePath = dialog.SelectedPath;
        }));

        invoking.Wait();

如果要創建單獨的線程,可以將ApartmentState設置為STA,這將使您無需調用即可調用UI對話框。

        Thread testThread = new Thread(method);
        testThread.SetApartmentState(ApartmentState.STA);
        testThread.Start();

因為您遇到了STA異常,所以這意味着您可能正在后台線程上運行。

InvokeRequired / BeginInvoke模式調用對話框:

if (InvokeRequired)
{
        // We're not in the UI thread, so we need to call BeginInvoke
        BeginInvoke(new MethodInvoker(ShowDialog)); // where ShowDialog is your method

}

請參閱: http : //www.yoda.arachsys.com/csharp/threads/winforms.shtml 請參閱: 單線程單元問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM