在单击鼠标时尝试从列表框中打开文件时出现问题 [英] Problem in trying to open a file from list box on mouse click

查看:98
本文介绍了在单击鼠标时尝试从列表框中打开文件时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

namespace DirList1
{
    public partial class Form1 : Form
    {
        const string rootFolder = @"C:\MyDoc";
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            {
                DirectoryInfo dinfo = new DirectoryInfo(rootFolder);
                FileInfo[] Files = dinfo.GetFiles("*.*");
                foreach (FileInfo file in Files)
                {
                    listBox1.Items.Add(file.Name);
                }
            }
        }
        private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

         Process.Start("notepad.exe", rootFolder + @"\" + (sender as ListBox).SelectedItem.ToString());
        }
        private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
        }
    }
}

推荐答案

你是否只有notepad兼容文件?如果您有多种文件类型,并且您希望操作系统决定使用哪个应用程序打开文件,请使用以下代码:

尝试使用:

Are you just having notepad compatible files? if you have multiple file types and you want OS to decide which application to use for opening the files, use below code:
Try to use:
Process.Start(rootFolder + @"\" + (sender as ListBox).SelectedItem.ToString());


进行这些更改,然后呢应该工作。



make these changes, then it should work.

// Another string to contain path and file.
string resultFilePath;
...
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    resultFilePath= rootFolder + @"\" + (sender as ListBox).SelectedItem.ToString();
}

private void button1_Click(object sender, EventArgs e)
{
    Process.Start("notepad.exe", resultFilePath);
}





还要确保控制事件正常。我已经看到有人会剪切和粘贴事件代码,但事件没有连接到控件。



您可能还想将文件类型过滤为intrest的文件类型,例如,如果你只想查看文本文件使用以下内容..



Also make sure the control events are working. I have seen where someone will cut and paste event code but the event is not connected to the control.

You may also want to filter the file type to those of intrest, for instance if you only want to see text files use the following..

FileInfo[] Files = dinfo.GetFiles("*.txt");


这篇关于在单击鼠标时尝试从列表框中打开文件时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆