OpenFileDialog always shows *.URL (Internet Shortcut files)
My OpenFileDialog
has one single Filter
which is also the DefaultExt
. I wonder why, when the dialog opens, I also get all the Internet Shortcuts listed (it is OK to get the shortcuts to folders, for instance, but not the *.URL files).
Is there some magic switch which I can turn on in order to net get them included in the list displayed to the user?
Currently, I have to handle the condition in the FileOk
event handler by setting e.Cancel
to true
if I detect that the user selected an *.URL
file (it is not working 100% of the time either,开发者_如何学C some shortcuts seem still to be getting through the FileOk
filter). Not getting them in the list in the first place would be better, though.
You're correct that Windows' Open File common dialogs show Internet Shortcuts along with folders. I have no idea why this behavior exists, but it's there- and it happens in Win32 (try Notepad to verify) as well as WinForms apps.
There is a way to work around this, but warning: it's hacky! If you derive a custom file dialog class from the FileDialog class, you get access to a few protected events that you can use to customize every aspect of the FileDialog's operation.
Dino Esposito wrote an MSDN Magazine article in November 2003 that shows how this technique works. This article is no longer on the MSDN site but you can get it on the wayback machine's archive here: http://web.archive.org/web/20150117123625/http://msdn.microsoft.com/en-us/magazine/cc300434.aspx.
What you'd probably have to do is to hook or subclass the WndProc of the file dialog, manually look through the file list control, identify entries that were shortcuts, and send Windows messages to the file list control to remove those items. Then you'd need to watch for refreshes of that list (e.g. from a directory change) and repeat the filtering operation.
This would be a huge hack, but it's possible.
If this is too much work or the hackiness is too much, I'd suggest just using the FileOk event to prevent users from selecting a shortcut by returning Cancel=true
from your CancelEventHandler for the FileOk event.
Annoying. You can whack them by implementing a handler for the FileOk event so the user can never select one:
private void openFileDialog1_FileOk(object sender, CancelEventArgs e) {
string ext = System.IO.Path.GetExtension(openFileDialog1.FileName);
if (String.Compare(ext, ".url", true) == 0) e.Cancel = true;
}
精彩评论