How to create customized open file dialog in C#

2019-01-26 18:19发布

问题:

How can one create a user control that has the same functionality (along with some extended features) of OpenFileDialog in C#? I've followed this, but I could not find a solution for my problem.

My requirement is to add an extra button in the dialog. If that button gets clicked then the parent should be notified in the same manner as the ok and cancel buttons do.

回答1:

The OpenFileDialog is a sealed class, and as such can't be inherited or extended. Your best bet would be to write your own open file dialog.

On the other hand, the FileDialog class isn't sealed, so you could inherit from that and make the necessary customizations. See http://www.codeproject.com/KB/dialog/OpenFileDialogEx.aspx for more information



回答2:

OpenFileDialog is a Windows built-in feature (it's non-.NET at all), so extending it is quite a nontrivial task. Why don't you just build it from scratch or look for any existing solutions?



回答3:

You most likely need to use the raw Windows interface to achieve this. At a high level you do this:

  1. Create an instance of IFileOpenDialog.
  2. Query this for a reference to the IFileDialogCustomize interface.
  3. Use the AddPushButton method to add your button.
  4. Call Advise on the IFileOpenDialog interface to register your interface to handle events. That interface is IFileDialogControlEvents and is implemented by you. You have to implement both that interface and IFileDialogEvents.
  5. Your IFileDialogControlEvents.OnButtonClicked method is called when the button is pressed.

This is only available in Vista. If you need to support XP then you need to use GetOpenFileName and supply a resource template for your customisation. That's really no fun at all, especially from managed code! A C++/CLI library makes this a bit more manageable.