Disable Right click in FolderBrowserDialog dialog box - wpf? - c#

System.Windows.Forms.FolderBrowserDialog dlg = new FolderBrowserDialog();
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
System.Windows.Forms.DialogResult result = dlg.ShowDialog(win);
I have used this to get the folder dialog box but now i need to disable right click in that folder dialog box, so that i can prevent deletion of folders from there..enter code here
Creating a custom folderDialog box is the last option i want to take..
So, Could some one suggest any possible solution for this without custom folderDialog.

You can't. The class cannot be inherited so you can't override any of the settings. There are no events to hook into.
So you have a couple options:
Roll Your Own
Use the file system to lock down your user environment.
Buy a third party control that has this functionality.
We opted for option 2, because the end users did not need to use "normal" windows apps/file locations on our RDP server, they just needed to run our application. The Organizational Unit (OU) they are added to applies permissions that they only had access to the folders we wanted them to have access to. They can't see any of the normal items you would see when the dialog is shown, but can create folders, save items, load items from the folders we give them permission to use.

Ravindra,
Since Delete in the ContextMenu is a windows feature, you would have to modify the registry settings.
In essence you have to modify/delete the Delete registry entry & after your code executes you must restore it.
You can find the registry entry under: HKEY_CLASSES_ROOT. (You would indeed take some time to figure out this entry).
Ex:
System.Windows.Forms.FolderBrowserDialog fd = new System.Windows.Forms.FolderBrowserDialog();
//Get key for New menu option in Context menu.
RegistryKey key = Registry.ClassesRoot.OpenSubKey(#"Directory\Background\shellex\ContextMenuHandlers\New",true);
//Set it to blank.
key.SetValue("", "");
fd.ShowDialog();
//Restore the value.
key.SetValue("", "{D969A300-E7FF-11d0-A93B-00A0C90F2719}");`

Related

Limit a folder browser dialog to only folders containing specific files

I have a folder browser dialog (simple enough) but I only want it to be 'ok' if the folder contains files of a certain extension. What I have so far:
FolderBrowserDialog pDlg = new FolderBrowserDialog();
if (pDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if (Directory.GetFiles(pDlg.SelectedPath, "*.ext").Length > 0)
{
SrcDir.Text = pDlg.SelectedPath;
}
else
{
DBox.Items.Insert(0, "Not a suitable folder");
}
}
This works in limiting the population of the textbox SrcDir if the selected folder does not contain any of the right sort of files (*.ext). It would be preferable if I could disable the 'ok' button when the folder is selected in the dialog if GetFiles(..).Length == 0 so an unsuitable folder just cannot be selected; as you cannot 'see' the files in the FolderBrowserDialog it's kind of hard for the user to know if it is the right folder, so by changing the enabled state of the OK button would indicate to the user if the folder is suitable.
I could use a OpenFileDialog to browse for one file in the directory and then use FileInfo.DirectoryName to extract the folder that its in, but I am under pressure not to do it that way (others think it's sloppy).
I am fairly sure this can't be done with a standard FolderBrowserDialog; is there another in-built dialog class that I can control this behavior or should I create a new form with a DirectorySearcher or similar TreeView and .ShowDialog() on a custom dialog form?

Ookii VistaFolderBrowserDialog and getting selected folder

I am trying to use the Ookii dialog pack to spawn the new Vista style folder selection dialog. That all works with this simple code:
VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();
dlg.SelectedPath = Properties.Settings.Default.StoreFolder;
dlg.ShowNewFolderButton = true;
dlg.ShowDialog();
However, I cannot see any way of knowing when the user has selected a folder as there are no events on this object. I could poll for changes in SelectedPath, but that seems a terribly inefficient way of doing things.
Is there some generic C# trick I have missed to enable me to know when a user has selected a folder and therefore update other fields appropriately?
Try
VistaFolderBrowserDialog dlg = new VistaFolderBrowserDialog();
dlg.SelectedPath = Properties.Settings.Default.StoreFolder;
dlg.ShowNewFolderButton = true;
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = dlg.SelectedPath;
}
Simple answer from 2023 for WPF for future people who hate sifting through stackoverflows endless incorrect answers and needless fluff.
This answer uses Ookii.Dialogs.WPF NuGet package you can install from right inside visual studio. At the top left click Project -> Manage NuGet Packages... -> Go to browse tab and search OOkii.Dialogs.Wpf then install it. Now this code will work. :)
You can directly copy paste this.
VistaFolderBrowserDialog FolderSelect = new VistaFolderBrowserDialog(); //This starts folder selection using Ookii.Dialogs.WPF NuGet Package
FolderSelect.Description = "Please select the folder"; //This sets a description to help remind the user what their looking for.
FolderSelect.UseDescriptionForTitle = true; //This enables the description to appear.
if ((bool)FolderSelect.ShowDialog(this)) //This triggers the folder selection screen, and if the user does not cancel out...
{
TextBoxGameFolder.Text = FolderSelect.SelectedPath; //...then this happens.
}
```

Ideas on how to remember previous user selections on .NET WinForm

I am currently looking at a better approach to remember/persist previous state of the controls on a .NET Windows Form.
For example, there are 5 drop down list menu controls on a windows form. And user previously selected some items in these drop down menu. What I'd like to do here is: when this WinForm is loaded again, user's previous selections shall be recovered and remain the same.
For now, I can kinda think of a solution: store each selected value/index in a text file or registry key or something. And then read them every time the From is loaded.
But the thing is this approach would become inefficient to deal with a large number of controls and maintain their states.
So can anyone give me some thoughts or suggestions? What'd be the best way to do achieve it?
EDIT:
I just had a read about this article on MSDN, and this concerns me because I am doing the add-in project at the moment:
You cannot use application settings in an unmanaged application that
hosts the .NET Framework. Settings will not work in such environments
as Visual Studio add-ins, C++ for Microsoft Office, control hosting in
Internet Explorer, or Microsoft Outlook add-ins and projects.
You might want to look at Settings files
Saving User Settings
private void UserSettingsDemo_Load(object sender, EventArgs e)
{
txtServer.Text = Settings.Default.ServerNameSetting;
txtDatabase.Text = Settings.Default.DBNameSetting;
txtPassword.Text = Settings.Default.PasswordSetting;
txtUserId.Text = Settings.Default.UserIdSetting;
}
private void UserSettingsDemo_FormClosing(object sender, FormClosingEventArgs e)
{
Settings.Default.DBNameSetting = txtDatabase.Text;
Settings.Default.UserIdSetting = txtUserId.Text;
Settings.Default.PasswordSetting = txtPassword.Text;
Settings.Default.ServerNameSetting = txtServer.Text;
Settings.Default.Save();
}
Are you talking about keeping the previous state of a control after restarting the application? In that case, you probably won't have no choice than writing all the changes down in an configuration file for example.
If you are trying to navigate between different winforms and want to persist the changes, you could implement an history of controls. A datastructur like a stack should do the trick, with the following methods:
AddToHistory(Control control)
RetrieveLastOpen()
As far as you know what exactly you want to save it is ok to use smth like
(foreach var child in MainForm.Children.OfType<ComboBox>)
{
// Save properties of child into Dictionary<string, ComboBoxProperties>
}
and for loading you will do smth like this
(foreach var child in MainForm.Children.OfType<ComboBox>)
{
// Load properties of child from dictionary[child.Name]
}

Saving and restoring app settings in C# Forms

I have a C# Dialog based app. I want to save the preferences/settings the user choose, so that I could reload them in the next run.
I am new to C#, may be this is something quite basic but I do not know.
Do I have to explicitly write them to a file like ini or something ? or is there a built in way to do that.
The kind of config data is like checkboxes selelected, numericUpDOwn, checkedListbox - checked items etc
Select the control in the designer. Scroll all the way up in the Properties window and expand (ApplicationSettings). Click the indicated button to open a dialog. Select the property whose value should be persisted (like Checked for a check box) and click New in the dropdown.
Be a bit careful, not all properties are suitable to be persisted like this. An example is the form's Size. You don't want to store the size when the form is minimized or maximized, that size won't restore well. You need to do this by adding the setting in the Settings designer an only write it when the control is in the right state. In the case of Size, that's when the Resize event runs and the WindowState is Normal.
After you create the application settings as the other answers suggest, make sure you don't forget to call Properties.Settings.Default.Save(), for example:
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Properties.Settings.Default.Save()
}
To Create a New Setting at Design Time
In Solution Explorer, expand the Properties node of your project.
In Solution Explorer, double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings.
In the Settings designer, set the Name, Type, Scope, and Value for your setting. Each row represents a single settings
For more info you can refer here
You should use application settings. These will persist their values after you close your application, and you will be able to read from them when the program starts back up again.

Programmatically change the icon of the executable

I am developing an application called WeatherBar. Its main functionality is based on its interaction with the Windows 7 taskbar — it changes the icon depending on the weather conditions in a specific location.
The icons I am using in the application are all stored in a compiled native resource file (.res) — I am using it instead of the embedded resource manifest for icons only. By default, I modify the Icon property of the main form to change the icons accordingly and it works fine, as long as the icon is not pinned to the taskbar. When it gets pinned, the icon in the taskbar automatically switches to the default one for the executable (with index 0 in the resource file).
After doing a little bit of research, I figured that a way to change the icon would be changing the shortcut icon (as all pinned applications are actually shortcuts stored in the user folder). But it didn't work.
I assume that I need to change the icon for the executable, and therefore use UpdateResource, but I am not entirely sure about this. My executable is not digitally signed, so it shouldn't be an issue modifying it.
What would be the way to solve this issue?
If you want to do this programatically, I would start by looking at the Portable Executable file format (Wikipedia entry). The resources section (.rsrc, see section 6.9) should contain the icon. Using this information, you can write a tool to modify the icon.
If you just want to quickly change an icon in an existing file, you might be able to hack it up in the Visual Studio resource editor. I tested this with a file by deleting the old icon and adding a new one. The .exe icon changed in Explorer to the new icon, and the new icon appeared on the Start menu when I dragged it there.
-- Edit --
Yes, I agree that using UpdateResource is a good approach. Here is an example I found of using C++ functions to do so, and a P/Invoke signature for UpdateResource and FindResource.
private void button1_Click(object sender, EventArgs e)
{
String path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
String name = "test";
Shell32.Shell shl = new Shell32.ShellClass();
// Optional code to create the shortcut
System.IO.StreamWriter sw = new System.IO.StreamWriter(path + #"\" + name + ".lnk", false);
sw.Close();
// End optional code
Shell32.Folder dir = shl.NameSpace(path);
Shell32.FolderItem itm = dir.Items().Item(name + ".lnk");
Shell32.ShellLinkObject lnk = (Shell32.ShellLinkObject)itm.GetLink;
// Optional code to create the shortcut
lnk.Path = Environment.GetFolderPath(Environment.SpecialFolder.System)
+ #"\notepad.exe";
lnk.Description = "nobugz was here";
lnk.Arguments = #"c:\sample.txt";
lnk.WorkingDirectory = #"c:\";
// End optional code
lnk.SetIconLocation(Environment.GetFolderPath(Environment.SpecialFolder.System)
+ "cmd.exe", 1);
lnk.Save(null);
}
This was taken from http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/9e23a82c-8bed-4b96-8b9a-4c2b6136a622/
It may help.
I decided to implement a workaround - the icon will change in the thumbnail for the window (it is possible in Windows 7). If the icon is unpinned, the user can see the icon changing. In case it is pinned, the thumbnail will change according to the current weather conditions.
Seems to me like the structure of pinned icons (being a shortcut, in fact) doesn't allow dynamic icon change. If I am wrong, I am open for comments and ideas on this.

Categories

Resources