打开时需要来自 DataGridView C# 的对话框

本文关键字:DataGridView 对话框 | 更新日期: 2023-09-27 18:34:46

我有一个Windows窗体,其中我有一个DataGridView,用于显示某个位置的文件列表。我创建了一个上下文菜单,右键单击文件名即可下拉。菜单中的选项是"复制","打开方式"等。

当我单击菜单中的"打开方式"时,我需要像在Windows中一样获取"打开方式"对话框,然后我应该能够选择可以打开文件的应用程序。

我不确定如何获取"打开方式"对话框。有人可以帮我吗?

提前感谢!!

打开时需要来自 DataGridView C# 的对话框

这可能是您正在寻找的内容,只需更改需要更改的内容以适应您的应用程序即可。

打开文件对话框并使用 WPF 控件和 C# 选择一个文件

试试这个:

using System.Diagnostics;
//...
private void openWith_Click(object sender, System.EventArgs e)
{
    Stream myStream = null;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.InitialDirectory = "c:''" ;
    openFileDialog1.Filter = "application (*.exe)|*.exe" ;
    openFileDialog1.FilterIndex = 2 ;
    openFileDialog1.RestoreDirectory = true ;
  if(openFileDialog1.ShowDialog() == DialogResult.OK)
  {
    try
    {
      ProcessStartInfo pi = new ProcessStartInfo();
      pi.Arguments = Path.GetFileName(file);//the file that you want to open
      pi.UseShellExecute = true;
      pi.WorkingDirectory = Path.GetDirectoryName(file);
      pi.FileName = openDialog1.FileName;
      pi.Verb = "OPEN";
      Process.Start(pi);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not open the file with this program. Original error: " + ex.Message);
    }
  }
}

您可以使用 ShellExecuteEx 函数。
该示例的用法OpenWith("Path to File");

        [Serializable]
    public struct ShellExecuteInfo
    {
        public int Size;
        public uint Mask;
        public IntPtr hwnd;
        public string Verb;
        public string File;
        public string Parameters;
        public string Directory;
        public uint Show;
        public IntPtr InstApp;
        public IntPtr IDList;
        public string Class;
        public IntPtr hkeyClass;
        public uint HotKey;
        public IntPtr Icon;
        public IntPtr Monitor;
    }
    // Code For OpenWithDialog Box
    [DllImport("shell32.dll", SetLastError = true)]
    extern public static bool
           ShellExecuteEx(ref ShellExecuteInfo lpExecInfo);
    public const uint SW_NORMAL = 1;
    static void OpenWith(string file)
    {
        ShellExecuteInfo sei = new ShellExecuteInfo();
        sei.Size = Marshal.SizeOf(sei);
        sei.Verb = "openas";
        sei.File = file;
        sei.Show = SW_NORMAL;
        if (!ShellExecuteEx(ref sei))
            throw new System.ComponentModel.Win32Exception();
    }