在我的程序中,我需要强制用户选择保存文件夹。我这样做是通过将SelectedPath设置为MyComputer。
我的问题是最初没有禁用“确定”按钮。
行为:
我尝试过使用SelectedPath和RootFolder,以及Environment.SpecialFolder.MyComputer和Environment.GetPath()都无济于事。
当SelectedPath不是有效文件夹时,如何禁用“确定”按钮?
修改 它在Windows XP,.Net 4.0上运行,在Visual Studio 2010 Professional中开发。
编辑#2:已添加完整示例代码。
using System;
using System.Windows.Forms;
using System;
using System.Windows.Forms;
namespace FolderBrowser
{
public class Form1 : Form
{
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Button button1;
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
this.button1.Location = new System.Drawing.Point(10, 10);
this.button1.Text = "Open FolderBrowserDialog";
this.button1.Click += new System.EventHandler(this.SelectSaveFolderItem_Click);
this.Controls.Add(this.button1);
this.ResumeLayout(false);
}
public Form1()
{
InitializeComponent();
}
private void SelectSaveFolderItem_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.SelectedPath = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}";
fbd.ShowDialog();
}
}
答案 0 :(得分:1)
参考:MSDN: Disable a button in a folder browser dialog
在上面的msdn线程中,用户希望在目录不存在时禁用文件夹浏览器对话框中的接受按钮。我觉得这与你的问题有关:
How can I disable the OK button when the SelectedPath is not a valid folder?
该线程中的解决方案是在显示对话框后使用Timer事件禁用OK按钮。我将VB.Net代码转换为C#:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
public class Form1
{
[DllImport("user32.dll", EntryPoint = "FindWindowA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowExA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 FindWindowEx(Int32 hWnd1, Int32 hWnd2, string lpsz1, string lpsz2);
[DllImport("user32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 EnableWindow(Int32 hwnd, Int32 fEnable);
private void Button1_Click(System.Object sender, System.EventArgs e)
{
Timer1.Enabled = true;
FolderBrowserDialog fld = new FolderBrowserDialog();
fld.ShowDialog(this);
}
private void Timer1_Tick(System.Object sender, System.EventArgs e)
{
Int32 hwndMainWindow = default(Int32);
hwndMainWindow = FindWindow("#32770".Trim(), Constants.vbNullString);
// '#32770 (Dialog)#32770 (Dialog)
if (hwndMainWindow) {
Int32 hwndBtn = default(Int32);
hwndBtn = FindWindowEx(hwndMainWindow, IntPtr.Zero, "Button", "OK");
if (hwndBtn) {
EnableWindow(hwndBtn, 0);
}
}
Timer1.Enabled = false;
}
}