1,105,581 Community Members

How to open file location from list view item using context menu strip?

Member Avatar
Junior Poster in Training
78 posts since Dec 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]

Here is list of things I want to do:

Display context menu strip only when mouse is over the item and right clicked on it, the code I have for that is this:

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
            if (listView1.SelectedItems.Count == 0)
                e.Cancel = true;

        private void contextMenuStrip1_MouseClick(object sender, MouseEventArgs e)
            if (e.Button == MouseButtons.Right)
                Point pt = listView1.PointToScreen(e.Location);

The problem about this code is longest the item is selected it will display the menu strip, what I don't want is the context menu strip shouldn't show up unless directly right clicked on the item.

I have 3 options on the context menu strip, open, open file location and properties. If user right clicks the item and says open, its should ask the user what do you want to open it with using Windows explorer! For the open file location, I came up with this:

Process.Start("explorer.exe", "I need filepath from listview item");

That does open the custom location, however since there is going to be lots of files in the list view, I need the program to get the file location it self.

The implementation I have for the scanning files and displaying them on list view is:

private void button1_Click(object sender, EventArgs e)


            string[] directories = new string[] { 

            string[] extensions = new string[] { "*" };

            foreach (var dir in directories)
                var dirInfo = new DirectoryInfo(dir);
                foreach (var ext in extensions)
                    foreach (var fileInfo in dirInfo.GetFiles(ext))
                        listView1.Items.Add(new ListViewItem(new string[] { fileInfo.Name, Path.GetDirectoryName(fileInfo.FullName) + @"\", SizeUnit.FileSizeToString(fileInfo.Length) }));

Hope that can help you a bit, if you need to know more ask, I also have a code to calculate the size of the file, i didn't insert is because I don't think you will need it really. If anything is not clear plz do ask and thank you very much all helps are appreciated.

This article has been dead for over three months: Start a new discussion instead
Start New Discussion
View similar articles that have also been tagged: