Load winforms icon from folder dynamically - c#

I need to change the winform icon to an icon found in a directory. This needs to work in the same way a web browser handles the loading of website icons.

If this is going to be dynamic you can use a FileSystemWatcher and monitor the created and changed events in your Folder for your file changes.
private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
if (e.Name == "myIcon.ico")
{
this.Icon = new Icon(e.FullPath);
}
}

Set Icon property in constructor or Load event of form (make sure that icon exist in application directory):
Icon = new Icon("favicon.ico");

Related

Set WPF Checkbox value on window draw (not application start)

I have been searching for this for ages now and still have no idea how to achieve it, this is my first C#/WPF application so it is entirely possible that I have seen the answer and just not known it, apologies if it is really easy.
I have a winForms application that launches a WPF window (the winForms is because the app is a system tray icon that spawns other windows). The only WPF window I have currently has two checkboxes that I have managed to store the value of in app.config, that value is also successfully applied to the checkboxes when the application first starts. However I cannot work out how to have the value applied to the checkbox every time the window is opened.
The window is opened by this (with an attempt to fix it commented out):
private void notifyIcon1_DoubleClick(object Sender, EventArgs e)
{
var RestartPortal = new RestartPortal();
//RestartPortal.InvalidateVisual();
RestartPortal.Show();
}
The values are applied to the window on application run with this (along with another attempt):
public RestartPortal()
{
InitializeComponent();
alwaysOnTopCheck.InvalidateVisual();
closeWhenCompleteCheck.InvalidateVisual();
alwaysOnTopCheck.IsChecked = bool.Parse(ConfigurationManager.AppSettings.Get("onTopChecked"));
closeWhenCompleteCheck.IsChecked = bool.Parse(ConfigurationManager.AppSettings.Get("autoCloseChecked"));
}
If can help out I will be incredibly appreciative.
Thank you.
Edit: In testing I have noticed that the checkboxes seem to be remembering the value that they were assigned when the application first ran, even stranger they force this value into the app.config file each time the window is loaded. To explain better:
Run application
Load Window
Load config in notepad and check that the values correlate
(close notepad) Uncheck checkboxes
Open config file in notepad again to check that values have been saved correctly.
Close window
Open window
Open config file (again in a fresh notepad) and see that the values correlate and that by opening the window the values have been forced back to the values they held when the application was first run.
To my mind the only way that this can be happening is if somehow something is calling the event handlers for the checkboxes as that is the only place that can save to the app.config file. I am now even more confused than I was before, in case it helps here is the XAML for the checkboxes:
<CheckBox x:Name="closeWhenCompleteCheck" Margin="5" HorizontalAlignment="Left" Content="Close when complete" Checked="closeWindow_Checked" Unchecked="closeWindow_Unchecked"/>
<CheckBox x:Name="alwaysOnTopCheck" Margin="5" HorizontalAlignment="Left" Content="Always on top" Checked="onTop_Checked" Unchecked="onTop_Unchecked"/>
And here is the c# for the checked and uncheckeds (though only for one checkbox as they are identical):
private void onTop_Checked(object sender, RoutedEventArgs e)
{
this.Topmost = true;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["onTopChecked"].Value = (alwaysOnTopCheck.IsChecked).ToString();
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("AppSettings");
}
private void onTop_Unchecked(object sender, RoutedEventArgs e)
{
this.Topmost = false;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["onTopChecked"].Value = (alwaysOnTopCheck.IsChecked).ToString();
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("AppSettings");
}
Any help will be very much appreciated as ever (and probably save my sanity at this point).
Thank you.
You should try utilizing the Loaded event instead of the constructor. If your window closes, but the variable storing it does not get destroyed, your constructor will not be called again.
public RestartPortal()
{
InitializeComponent();
// Subscribe to the Loaded event
this.Loaded += RestartPortal_Loaded;
}
void RestartPortal_Loaded(object sender, RoutedEventArgs e)
{
// Set your values here
alwaysOnTopCheck.IsChecked = bool.Parse(ConfigurationManager.AppSettings.Get("onTopChecked"));
closeWhenCompleteCheck.IsChecked = bool.Parse(ConfigurationManager.AppSettings.Get("autoCloseChecked"));
}

how to open listview window explorer in listview control

i have a listview window browser thats working completely fine .i open folder through folder browser and the files and folders in that particular directory opens in the listview via using
PopulateListView(path)
now in my mouse double click event im opening a particular file and folder it opens the file but when it opens the directory a new window pops up .i want that directory to b opened in the listview control...the code for this scenarioa is
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
string pathdoubleClicked = listView1.FocusedItem.Tag.ToString();
PopulateListView(pathdoubleClicked);
Process.Start(pathdoubleClicked);
simpleStack.Push(pathdoubleClicked);
}
now i want to do it with if else like if the path is of drectory then go to populatelistview method other wise process.start but its now working any idea how can i do this
From what I understand, if the path is a directory, you want to display its content on double-click. If it's a file, you want to open it.
So you would simply do:
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
string pathdoubleClicked = listView1.FocusedItem.Tag.ToString();
if (System.IO.Directory.Exists(pathdoubleClicked))
{
PopulateListView(pathdoubleClicked);
}
else
{
Process.Start(pathdoubleClicked);
}
// ?
simpleStack.Push(pathdoubleClicked);
}

No Image display in c#

I created a simple windows form application C#, that is supposed to show a picture. I am following a tutorial from here Following is the code of form1.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
// Construct an image object from a file in the local directory.
// ... This file must exist in the solution.
Image image = Image.FromFile("Picture1.png");
// Set the PictureBox image property to this image.
// ... Then, adjust its height and width properties.
pictureBox1.Image = image;
pictureBox1.Height = image.Height;
pictureBox1.Width = image.Width;
}
}
The image is present in the solution folder, but still nothing is displayed in the window when the application is run. There is no compilation error.
Update
Its solved now.
Make sure the PictureBox click event handler is registrated. It is not sufficient to copy the example code. (I'm just guessing)
Without a full path, the image won't load from the solution directory.. it will load from the directory where your executable is executed from.. which is either the Debug or Release folders when you're running from Visual Studio.. depending on what Profile you're running it with.
So put the image in the /bin/Debug folder and run your program again.
A better option would be to add this image to the project and do either of the two:
Add as a resource. It can later be used with strong typing.
Set this option on the file: Copy to Output Directory = Copy if newer.
It is not a good practice to add anything manually under /bin/, because those folders are volatile and can be erased by Visual Studio at any moment (usually on the next rebuild).

Save back color

How can I change and save the back color in a C# Windows Application so that when I
close the application and run the program again the new color will be the
back color default?
You can get that going with very little effort. Select the form in the designer, in the Properties window open the ApplicationSettings node. Select (PropertyBinding) and click the button. Select BackColor in the popup dialog. Click the dropdown arrow and click New. Set the name to, say, "FormBackColor".
The only other thing you need is an option to let the user pick another color. Very easy to do with the ColorDialog class:
private void OptionChangeColor_Click(object sender, EventArgs e) {
using (var dlg = new ColorDialog()) {
if (dlg.ShowDialog() == DialogResult.OK) {
this.BackColor = Properties.Settings.Default.FormBackColor = dlg.Color;
Properties.Settings.Default.Save();
}
}
}
You'll need to save the new color in some file that you load on startup and apply as the background color.
Or use a user setting like this.
You could do something simple like File.WriteAllText("bg.txt", this.BackColor.ToString()); and when the app loads do this.BackColor = Color.FromName(File.ReadAllText("bg.txt"));
Of course storing this color in Isolated Storage or in the registry might be better. But you get the idea...
Some time ago there was thread about best practices to do that here on stackoverflow. Please take look: Best practice to save application settings in a Windows Forms Application

Retaining the changes made to the backcolor property

I am developing a windows application.
I have 3 forms:
I want to change the backcolor of all the 3 forms to the color selected by the user.
I have used the following code I am able to change the backcolor but When I exit the application and restart it I am not able to get the color that user has set. I am getting the default colour only.
Is it possible to retain the colour selected by the user and use it as backcolor when the user restarts the application.
CODE
In Form1
ColorDialog c1 = new ColorDialog();
public static System.Drawing.Color bkc;
private void button1_Click(object sender, EventArgs e)
{
DialogResult res = c1.ShowDialog();
if (res == DialogResult.OK)
{
bkc = c1.Color;
this.BackColor = bkc;
MessageBox.Show(Convert.ToString(bkc));
}
}
private void button2_Click(object sender, EventArgs e)
{
Form2 obj1 = new Form2();
obj1.BackColor = bkc;
obj1.Show();
}
In Form 2
CODE
private void button2_Click(object sender, EventArgs e)
{
Form3 obj1 = new Form3();
obj1.Show();
}
private void Form2_Load(object sender, EventArgs e)
{
this.BackColor = Form1.bkc;
}
In Form3
CODE
private void button2_Click(object sender, EventArgs e)
{
Form1 obj1 = new Form1();
obj1.Show();
}
private void Form3_Load(object sender, EventArgs e)
{
//Form1 obj2 = new Form1();
this.BackColor = Form1.bkc;
}
In the color dialog box I am selecting a color and pressing Ok button the color is also changed but when I restart the application I dont get the colour which I set using the Color Dialog.I want to retain this setting so that the user can get the desired color without resetting it each time the application is executed.
The above code does not generate any error.
can anybody help me out in performing this task?
Thanks in advance!
You will need to save the value somewhere such as the Application.exe.config:
// Open App.Config of executable
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration
(ConfigurationUserLevel.None);
// Add an Application Setting.
config.AppSettings.Settings.Add("BackgroundColour",
bkc + " ");
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
// Force a reload of a changed section.
ConfigurationManager.RefreshSection("appSettings");
Here is a C# full code example: Using System.Configuration.ConfigurationManager Example
The suggestion of using the application configuration file is close, but there are two things wrong with it.
First, all users of the application share the same application configuration file. If you have multiple users (on a network, say, or different users on the same machine), storing a user's preference in the application configuration file will change that setting for all users. A second thing wrong with it is that under a default installation on Vista it won't work anyway: by default, Vista doesn't give the user write access to anything under the Program Files directory, so saving changes to the application configuration file will throw an exception.
The right answer is to use user settings. These get stored in the application's user settings file, which lives in a (deeply nested, and OS-version-dependent) subdirectory of the user's home directory. The ConfigurationManager loads these settings at runtime, and lets you update and save them in your code. There's an entire infrastructure built into Visual Studio to make this (relatively) easy, which is good, because doing it properly involves writing a spooky amount of code against the ConfigurationManager class. Here's how it works:
If you look under the Properties of your VS project, you'll see an item called Settings.settings. When you double-click on this, it will show you a grid that lets you add settings to your project. You give the setting name, choose its the data type and default value, and, crucially, the scope. The setting can be application scope, in which case its value will be common to all users of the application and be stored in the application configuration file. Or it can be user scope, in which case each user can have his own value for the setting, and the setting will live in the user settings file.
When you add a setting to this grid, VS generates code to make the setting available to your code. Basically, it creates a class that exposes these settings to your code as properties of a singleton object. (You can see this code if you want to get an idea of what this is saving you from having to do yourself; it gets stored in the 'Settings.Designer.cs' file created under 'Settings.settings' in the project view.) It also, conveniently, regenerates this class every time you change the information in the Settings grid. Once you create a setting in the settings grid, you can reference it in your code thusly:
ctl.BackColor = Properties.Settings.Default.BackColor;
User settings can be modified by your code:
Properties.Settings.Default.BackColor = newBackColor;
And you can save them to the user settings file like this:
Properties.Settings.Default.Save();
Having these settings being exposed as properties of a class is useful for a lot of reasons. One of the most important is that since they're properties (and not, say, dictionary entries accessed by a key, which is how most code that people write against the ConfigurationManager class works), there's compile-time checking of the names you're using in code. You're not ever going to get a NullReferenceException at runtime if you misspell the name of a setting; you'll get an error when you compile it instead.
There are a few subtleties to using user settings. One of the less obvious ones is: what happens when you produce a new release of the software? The user settings are stored in a directory that's keyed to the version number of the program; if you release a new version, the user settings file for it won't exist. How do you keep the user from losing all of his settings when he upgrades your program?
This is also built in to that Settings class; all you need to do is this:
if (Properties.Settings.Default.UpgradeSettings)
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.UpgradeSettings = false;
}
This will copy the user's settings from the previous release into the settings file for the new release.
Why dont you create an event that all three forms listen to and get them to change the background colour when listening to the "change colour" event? And you could store the colour in a static variable so that when the form gets loaded, the background colour could be set to that stored in the variable.
In order for the screen to remember the colour settings, why not store the colour selected in a user preferences file? Try the "IsolatedStorage" functionality to save a preferences file.
You are doing it wrong way.
How will the application remember the user choice of backcolor?
The app runs in memory & shows chosen backcolor till its terminated.
Read on this & take it forward.
EDIT: Also, it is not right thing to use Form1.BackColor in Form2.
Open Form1, change backcolor, close Form1 & open Form2 to see what happens (you might see that Form1 opens again).

Categories