C # System Application ListView control (3). Add the ContextMenuStrip right-click menu to open and delete files

Source: Internet
Author: User

The previous section describes how to use the TreeView control and ListView control to display disk directory information. However, it is not enough to only display information. We also need to perform specific operations. in the "personal computer usage history" project, I also need to add two methods: "Open File" and "delete file. the details are as follows:
In the first article "C # System Application TreeView Control (1). display the tree disk file directory and the loading icon", the following is displayed:
Http://blog.csdn.net/eastmount/article/details/19453107

Show the file loading information in article 2 "C # System Application ListView Control (2). Load file information under the selected node folder", as shown in: http://blog.csdn.net/eastmount/article/details/21241313

The third article mainly describes how to add a right-click menu bar "Open File" and "delete file" for the files displayed in the ListView control. Opening a file can open a specific file, the deleted file can be deleted to the recycle bin. as shown in:
Open a file

Delete an object

1. Add the ContextMenuStrip control.
First, add a ContextMenuStrip control (right-click the associated control to display the relevant menu), and add the "open file" and "delete file" columns in "Enter here, set the Name to openFileToolStripMenuItem and deleteFileToolStripMenuItem. (otherwise, the name is English)
Add a mouse event for the filesList (ListView) control. The Code is as follows:

# Region right-click the event and add the contextMenuStrip control private void filesList_MouseClick (object sender, MouseEventArgs e) {// disable multiple filesList selections. multiSelect = false; // right-click if (e. button = MouseButtons. right) {// filesList. contextMenuStrip = contextMenuStrip1; // String fileName = filesList is not displayed in the blank space only when data in the selected list is displayed. selectedItems [0]. text; // obtain the selected file name Point p = new Point (e. x, e. y); contextMenuStrip1.Show (filesList, p) ;}# endregion

Click the file to run the software. The corresponding menu bar is added.
Ii. Open a file
Now you need to add the file opening function. You need to customize the path and name of two global variable records to open the file.

// Global variable public string fileNamePublic = ""; // file name public string filePathPublic = ""; // file path

Assign values to the selected path in the AfterSelect event of the selected content, and add a Click event for openFileToolStripMenuItem. The Code is as follows:

# Region open a file // set the "open file" Name in the contextMenuStrip1 control to openFileprivate void openFileToolStripMenuItem_Click (object sender, EventArgs e) {// The file is not selected if (this. filesList. selectedItems. count = 0) return; // obtain the selected file var selectedItem = this. filesList. selectedItems [0]; // The Name Of The global variable file SubItems [1] indicates the name of the file fileNamePublic = filePathPublic + "\" + selectedItem. subItems [1]. text; // MessageBox. show (fileNamePublic); try {// instantiate a new Process class namespace using System. diagnostics; using (Process p = new Process () {p. startInfo. fileName = fileNamePublic; // specify the file path p. startInfo. createNoWindow = false; // start the program in the current window // specify the display style p. startInfo. windowStyle = System. diagnostics. processWindowStyle. normal; p. startInfo. useShellExecute = true; // use the shell of the operating system to start the process p. start (); // Start to open the file} catch (Exception msg) // Exception Handling {MessageBox. show (msg. message) ;}# endregion

It instantiates a Process class, specifies the ProcessStartInfo parameter, and calls the Start () method of Process to open the file.
3. delete an object
You can start preparing to delete a File by using File. delete, but the deleted file is not added to the recycle bin, and the system file cannot be accessed. therefore, the SHFileOperation shell function is used to implement file operations. add a Click event for deleteFileToolStripMenuItem. The Code is as follows:

# Region delete a file // delete a file to the recycle bin private const int FO_DELETE = 3; // Delete private const int FOF_SILENT = 0x0004; // do not display the progress bar prompt box private const int FOF_NOCONFIRMATION = 0x0010; // No dialog box private const int FOF_ALLOWUNDO = 0x0040 appears; // allow undo private const int FOF_NOCONFIRMMKDIR = 0x0200; // you do not need to confirm when creating the folder // Add the namespace using System. runtime. interopServices; [StructLayout (LayoutKind. sequential)] private struct SHFILEOPSTRUCT {public int hwnd; // parent window handle, 0 is desktop public int wFunc; // function flag FO_COPY copy FO_DELETE delete FO_MOVE move FO_RENAME rename public string pFrom; // source file or source folder public string pTo; // destination file or folder public int fFlags; // The flag of the control file FOF_ALLOWUNDO allows you to revoke FOF_CONFIRMMOUSE from using public bool fAnyOperationsAborted; public int hNameMappings; public string lpszProgressTitle ;} // SHFileOperation shell function implements the SHFILEOPSTRUCT structure of the file operation parameter [DllImport ("shell32.dll")] private static extern int SHFileOperation (ref SHFILEOPSTRUCT FileOp );////// Delete the file Delete ("c: \ test.txt", true) and Delete "c:/test. text" to the recycle bin /////////Private static int Delete (string sPath, bool recycle) {SHFILEOPSTRUCT FileOp = new SHFILEOPSTRUCT (); FileOp. hwnd = 0; FileOp. wFunc = FO_DELETE; // The operation is to delete the file FileOp. fFlags = 0; FileOp. fFlags = FileOp. fFlags | FOF_SILENT; FileOp. fFlags = FileOp. fFlags | FOF_NOCONFIRMATION; FileOp. fFlags = FileOp. fFlags | FOF_NOCONFIRMMKDIR; if (recycle) {FileOp. fFlags = FileOp. fFlags | FOF_ALLOWUNDO;} FileOp. pFrom = SPath + "\ 0"; return SHFileOperation (ref FileOp);} // set the "delete file" Name in the contextMenuStrip1 control to deleteFileprivate void deleteFileToolStripMenuItem_Click (object sender, EventArgs e) {// if (this. filesList. selectedItems. count = 0) return; // obtain the selected file var selectedItem = this. filesList. selectedItems [0]; // The Name Of The global variable file SubItems [1] indicates the name of the file fileNamePublic = filePathPublic + "\" + selectedItem. subItems [1]. text; // Mess AgeBox. Show (fileNamePublic); try {if (MessageBox. Show ("are you sure you want to delete this recently viewed file? "," Prompt ", System. windows. forms. messageBoxButtons. yesNo, System. windows. forms. messageBoxIcon. question) = System. windows. forms. dialogResult. yes) {// Delete the file Delete (fileNamePublic, true); // remove the file foreach (ListViewItem item in this. filesList. selectedItems) {this. filesList. items. remove (item) ;}} MessageBox. show (this, "the file is deleted successfully! "," Message prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information);} catch (Exception msg) // Exception Handling {MessageBox. Show (msg. Message) ;}# endregion

Iv. Summary
Finally, I hope this article will help you. these three articles mainly show how to use the C # TreeView control to load the disk directory information, and display the specific information in the ListView control. Right-click the ListView control and choose the ContextMenuStrip control menu bar. in these articles, you can implement the following in the project:
1. How to Use the TreeView control to add icons, add nodes, and expand events
2. how to Use the ListView control to load data, set the title header, add data, and listItem. subItems. add and so on, especially when the database processing and other operations or display information, it is often applied to the control display content
3. How to right-click the control and choose ContextMenuStrip from the menu bar, set its Item, and add corresponding response events to it
Finally, I hope the article will be helpful to you. If there are errors or deficiencies in the article, please try again. as shown in the final running effect of my series of articles, the high imitation 360 can implement various functions at the same time. For details, refer to each part of the blog:

Above open delete file source code address: http://download.csdn.net/detail/eastmount/7414709

(By: Eastmount original CSDNHttp://blog.csdn.net/eastmount/)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.