views:

126

answers:

2

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, 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.

+1  A: 

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;
}
Hans Passant
+1  A: 

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. See this MSDN Magazine article for more info.

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.

Justin Grant