Вызов FolderBrowserDialog при нажатии кнопки в WindowsForms
Пытаюсь реализовать код, чтобы при нажатии на кнопку в форме WindowsForms(Framework4.8) появлялось окно для выбора папки, куда, например, установлен интерпретатор Пайтон(т.е. где python.exe), чтобы, после выбора каталога, данный путь был в переменной. Которую можно в дальнейшем передавать в метод (ButSetupLib_Click) с целью запуска скрипта (метод ButFurther_Click) или установки библиотек для питона по указанному пути . Для вызова диалога выбора каталога взял код c docs.microsoft...:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
public class FolderBrowserDialogForm : System.Windows.Forms.Form
{
private FolderBrowserDialog folderBrowserDialog1;
private OpenFileDialog openFileDialog1;
private RichTextBox richTextBox1;
private MainMenu mainMenu1;
private MenuItem fileMenuItem, openMenuItem;
private MenuItem folderMenuItem, closeMenuItem;
private string openFileName, folderName;
private bool fileOpened = false;
// The main entry point for the application.
//[STAThreadAttribute]
//static void Main()
//{
// Application.Run(new FolderBrowserDialogExampleForm());
//}
// Constructor.
public FolderBrowserDialogForm()
{
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.fileMenuItem = new System.Windows.Forms.MenuItem();
this.openMenuItem = new System.Windows.Forms.MenuItem();
this.folderMenuItem = new System.Windows.Forms.MenuItem();
this.closeMenuItem = new System.Windows.Forms.MenuItem();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.mainMenu1.MenuItems.Add(this.fileMenuItem);
this.fileMenuItem.MenuItems.AddRange(
new System.Windows.Forms.MenuItem[] {this.openMenuItem,
this.closeMenuItem,
this.folderMenuItem});
this.fileMenuItem.Text = "File";
this.openMenuItem.Text = "Open...";
this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click);
this.folderMenuItem.Text = "Select Directory...";
this.folderMenuItem.Click += new System.EventHandler(this.folderMenuItem_Click);
this.closeMenuItem.Text = "Close";
this.closeMenuItem.Click += new System.EventHandler(this.closeMenuItem_Click);
this.closeMenuItem.Enabled = false;
this.openFileDialog1.DefaultExt = "rtf";
this.openFileDialog1.Filter = "rtf files (*.rtf)|*.rtf";
// Set the help text description for the FolderBrowserDialog.
this.folderBrowserDialog1.Description =
"Select the directory that you want to use as the default.";
// Do not allow the user to create new files via the FolderBrowserDialog.
this.folderBrowserDialog1.ShowNewFolderButton = false;
// Default to the My Documents folder.
this.folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;
this.richTextBox1.AcceptsTab = true;
this.richTextBox1.Location = new System.Drawing.Point(8, 8);
this.richTextBox1.Size = new System.Drawing.Size(280, 344);
this.richTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left |
AnchorStyles.Bottom | AnchorStyles.Right;
this.ClientSize = new System.Drawing.Size(296, 360);
this.Controls.Add(this.richTextBox1);
this.Menu = this.mainMenu1;
this.Text = "RTF Document Browser";
}
// Bring up a dialog to open a file.
private void openMenuItem_Click(object sender, System.EventArgs e)
{
// If a file is not opened, then set the initial directory to the
// FolderBrowserDialog.SelectedPath value.
if (!fileOpened) {
openFileDialog1.InitialDirectory = folderBrowserDialog1.SelectedPath;
openFileDialog1.FileName = null;
}
// Display the openFile dialog.
DialogResult result = openFileDialog1.ShowDialog();
// OK button was pressed.
if(result == DialogResult.OK)
{
openFileName = openFileDialog1.FileName;
try
{
// Output the requested file in richTextBox1.
Stream s = openFileDialog1.OpenFile();
richTextBox1.LoadFile(s, RichTextBoxStreamType.RichText);
s.Close();
fileOpened = true;
}
catch(Exception exp)
{
MessageBox.Show("An error occurred while attempting to load the file. The error is:"
+ System.Environment.NewLine + exp.ToString() + System.Environment.NewLine);
fileOpened = false;
}
Invalidate();
closeMenuItem.Enabled = fileOpened;
}
// Cancel button was pressed.
else if(result == DialogResult.Cancel)
{
return;
}
}
// Close the current file.
private void closeMenuItem_Click(object sender, System.EventArgs e)
{
richTextBox1.Text = "";
fileOpened = false;
closeMenuItem.Enabled = false;
}
// Bring up a dialog to chose a folder path in which to open or save a file.
private void folderMenuItem_Click(object sender, System.EventArgs e)
{
// Show the FolderBrowserDialog.
DialogResult result = folderBrowserDialog1.ShowDialog();
if( result == DialogResult.OK )
{
folderName = folderBrowserDialog1.SelectedPath;
if(!fileOpened)
{
// No file is opened, bring up openFileDialog in selected path.
openFileDialog1.InitialDirectory = folderName;
openFileDialog1.FileName = null;
openMenuItem.PerformClick();
}
}
}
}
Я пытался реализовать данный класс через создание экземпляра класса FolderBrowserDialogForm в коде исполнения при нажатии кнопки:
using System;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;
using Microsoft.WindowsAPICodePack.Dialogs;
namespace PRN_anomalies
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void ButSetupLib_Click(object sender, EventArgs e)
{
FolderBrowserDialogForm f = new FolderBrowserDialogForm();
f.ShowDialog();
}
private void ButSetupPy_Click(object sender, EventArgs e)
{
// Setup python-3.7.4-amd64
string path = "python\\python-3.7.4-amd64.exe";
if (File.Exists(path))
Process.Start(path);
else
MessageBox.Show("Файл не найден");
}
private void ButFurther_Click(object sender, EventArgs e)
{
// запуск распознавания аномалий
string fileName = "python\\open_window.py";
if (File.Exists(fileName))
Process p = new Process();
p.StartInfo = new ProcessStartInfo(@"C:\Python\python.exe", fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
p.WaitForExit();
else
MessageBox.Show("Файл не найден");
}
private void ButCancel_Click(object sender, EventArgs e)
{
// Отмена
this.Close();
}
}
}
В результате появляется обрезанное окно без кнопок и текста. Как правильно реализовать класс FolderBrowserDialogForm, так, чтобы исполнить задуманный функционал? Чтение файла не нужно, только передать в переменную путь к выбранной папке.
Ответы (1 шт):
Добавленный вручную класс FolderBrowserDialog.cs, где размещал код с примером - удалил. Проблема решилась через:
using System.Windows.Forms;
private void ButSetupLib_Click(object sender, EventArgs e)
{
// Выбор пути для установки библиотек Python
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
DialogResult result = folderBrowserDialog.ShowDialog();
if (result == DialogResult.OK)
{
string openPath = folderBrowserDialog.SelectedPath;
MessageBox.Show(openPath);
}
}