Same icon for all windows forms [duplicate] - c#

This question already has answers here:
Set same icon for all my Forms
(8 answers)
Closed 1 year ago.
I am working on a project where my requirement is that i have to use a same icon on all my windows forms . I have atleast 50 windows forms and many more had to be added . So is there a way to set a default icon for all windows forms rathee than doing manually on each form page .

you have multiple solution for this problem
best idea would be to inherit from a common base-Form that sets the Icon in the constructor.
from : Form or : System.Windows.Forms.Form to : MyCustomForm
and then just change MyCustomForm icon with write this line in MyCustomForm Cunstrunctor
this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
then you just change project icon from project properties > Application > Icon and Manifest > browse for a *.ico file and add it there.
this approach can change other property in all from for example font,size,anchor,...
If you have many forms like:
public class MyAppForm1 : Form {
...
}
Then instead of deriving from Form, then you create an intermediate MyIconForm:
public class MyIconForm : Form {
public MyIconForm() : base() {
this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
}
}
Then you just have to update all your forms to:
public class MyAppForm1 : MyIconForm {
...
}

The short answer is no, there is no central location where you can set the icon to be used by all forms in your project. You have to do it yourself. There are a bunch of methods you can use, including using reflection to set the backing field for Form.DefaultIcon during program initialization.
First step: get an icon.
There are a couple of options here. You can load an icon from a file, a resource or an embedded resource (yes, two different types of resource). Or the application icon, but you said you don't have one.
For standard resources:
Open project properties
Click Add Resource, Add Existing File and browse to your icon.
Icon is added to Properties.Resources with a property named after the file.
For content files (distributed with the application):
Add icon file to project (Add Existing Item)
Set file's Build Action property to Content.
Set file's Copy to Output Directory to Copy Always or Copy if newer.
Load icon using new Icon(iconFilename).
For embedded resources:
Add icon file to project (Add Existing Item)
Set file's Build Action to Embedded Resource.
Use Assembly.CurrentAssembly.GetManifestResourceStream to open the resource as a stream.
Of the three I'd choose standard resource for most things.
Making it work 1: Form Constructor
Add the appropriate loading code to every form's constructor:
public partial class Form1 : Form
{
public Form1()
{
// Using standard resource method
Icon = Properties.Resources.FormIcon;
InitializeComponent();
}
}
Making it work 2: Base Class
This is a fairly simple option, assuming you have control over the source for all of your forms and are OK with going through all of them to change their base class. The base class simply sets the form's icon during construction:
public class DefaultIconForm : Form
{
// Using content file method
private static readonly Icon _defaultIcon = new Icon("FormIcon.ico");
public DefaultIconForm()
{
Icon = _defaultIcon;
}
}
public partial class Form1 : DefaultIconForm
{
public Form1()
{
InitializeComponent();
}
}
You'll need to change all of your forms and remember to inherit from DefaultIconForm for all future forms.
Making it work 3: modify Form.DefaultIcon
This one is a slightly nasty trick that relies on reflection and could fail on you at some point, but it means not having to change any other code in your application.
Open your Program.cs file and add this method to the Program class:
private static void SetDefaultFormIcon()
{
var field = typeof(Form).GetField("defaultIcon", BindingFlags.Static | BindingFlags.NonPublic);
// And for completeness, this is the Embedded Resource method
using (var stream = typeof(Program).Assembly.GetManifestResourceStream($"{Application.ProductName}.FormIcon.ico"))
{
var ico = new Icon(stream);
field?.SetValue(null, ico);
}
}
Now call SetDefaultFormIcon() from main() to initialize.
As written it works on both .NET Framework and .NET 5 WinForms applications. There's no guarantee that the defaultIcon hidden static field won't change in future, so be prepared for it to break at some point.

Related

Does webview2 in winui3 not support changing the download location?

I used cefsharp, I need to generate folders according to certain rules and download the web content to the specified directory. I'm going to replace it with webview2. I find that there is no way to specify the default download directory. Do you have any way?
It may evolve in the future, but currently, you must define the WEBVIEW2_USER_DATA_FOLDER environment variable manually as explained here WebView2 Globals, something like this:
public sealed partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
Environment.SetEnvironmentVariable("WEBVIEW2_USER_DATA_FOLDER", #"c:\temp\mydata");
MyWebView.CoreWebView2Initialized += MyWebView_CoreWebView2Initialized;
}
private void MyWebView_CoreWebView2Initialized(WebView2 sender, CoreWebView2InitializedEventArgs args)
{
// udf will contain c:\temp\mydata
var udf = sender.CoreWebView2.Environment.UserDataFolder;
}
...
}

Access properties in App.xaml.cs from different project UWP

Like what I said in the title, how can we access the property in App in a different project? I want to access it from normal class like a service. Not in viewmodel. Hope we can do something like Application as App.
Access properties in App.xaml.cs from different project UWP
You may try to use one App.xaml.cs for the two projects. For example, if the second project wants to access App.xaml.cs in the first project without reference the first project, you may consider remove the App.xaml.cs which is belonged to the second project, and Add-ExitingItem to add the App.xaml.cs from the first project. In that case, the two projects will share the same App.xam.cs and then you can directly access the properties as Marian Dolinský mentioned.
Otherwise, the two projects may not be able to communicate with each other directly. If the above method is not suit for you, please detail why you need this feature and we may need to consider other ways without accessing the App.xaml.cs.
Method 1
You could cast Application.Current to App:
App app = (App)Application.Current;
app.YourProperty = something;
Method 2
Create some static property holding the reference of App. In my projects I do it by creating a new property called Current as follows:
// in App.xaml.cs
public static new App Current { get; private set; }
public App()
{
Current = this;
// Another code
}

Application.Current <- how does it work?

I am going through some WPF example I found.
I have a class here which is inherited from Application:
public partial class DataBindingLabApp : Application
{
private ObservableCollection<AuctionItem> auctionItems = new ObservableCollection<AuctionItem>();
public ObservableCollection<AuctionItem> AuctionItems
{
get { return this.auctionItems; }
set { this.auctionItems = value; }
}
}
As you can see this class have a property called AuctionItems.
Because it inherits from Application it also contains property called 'Current' which provides access to the Application instance (according to MSDN).
Then in the code I have:
((DataBindingLabApp)Application.Current).AuctionItems.Add(item);
I do not understand it.
Since we can have many classes which may inherit from Application then how we know that Application.Current actually contains object of class 'DataBindingLabApp'?
Thank you!
Because Visual Studio generates entry point in the partial generated class of custom application type(DataBindingLabApp in your case) by default (You can find it by searching in the root directory of solution).
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main() {
DataBindingLabApp app = new DataBindingLabApp();
app.InitializeComponent();
app.Run();
}
And after application has been ran Application.Current contains instanse of DataBindingLabApp.
Since we can have many classes which may inherit from Application
That isn't relevant. What matters is that there is only ever one instance of the Application class. The one-and-only application that's running. Be sure to distinguish types from objects.

How to add/edit project resources from within the code in C#?

I want to add or edit my C# project resources from within the code. For example I have a string called myString in project resources. Now I want to change the value of this string:
MyProject.Properties.Resources.myString = "NewStringValue";
But the compiler gives an error that this property is read only. I also want to add an image by browsing the image and adding it to the project resources.
Any idea how I can do this?
Thanks in advance.
P.S: I am using Windows Form.
Project -> Properties -> Resources -> open the resx file -> select images. There you can see the images in your project.
You can add new images by dragging them into that area.
This code will store the chosen images and load the last stored image at startup.
You may have to make it Observable or do something to make all the PictureBoxes update their image.
public class DefaultPicture
{
private static string settings = "picture.settings";
private System.Drawing.Bitmap image = new Bitmap(settings);
public Bitmap Image
{
get
{
return this.image;
}
set
{
this.image = value;
this.image.Save(settings);
}
}
}

ToolStripButton: what's wrong with assigning an image programmatically

There is a Form with a ToolStrip. This ToolStrip contains a ToolStripButton. I want to assign an image to this button:
this.btnSaveFile.Image = Bitmap.FromFile("C:\\Work\\Icons\\png\\save.png");
It works only if there is save.png on specified path. Otherwise, I get an FileNotFound Exception.
If I created a Form via Form Designer, Visual Studio would create a code like this:
this.toolStripButton9.Image = ((System.Drawing.Image) (resources.GetObject("toolStripButton9.Image")));
toolStripButton9.Image here is not a real name. Visual Studio takse my file save.png and transform it into toolStripButton9.Image.
But I create a form programmatically, without Designer. And my question is how to assign an image to the ToolStripBotton programmatically?
I tried to add the image to the project, but it didn't help much. I have no idea how to make Visual Studio grab it and embed into my executable so that I wouldn't need this file on specified location.
In MSDN, I only see the solution like that:
this.toolStripButton1.Image = Bitmap.FromFile("c:\\NewItem.bmp");
But it doesnt' work as I told above. I understand there is a simple solution but don't see it. Could you please give me a hint?
In Visual Studio, Open your "Properties" folder in the solution explorer, then open the Resources.resx file and add a existing image file as resource. You can then use it programmatically via the Resource static class:
Image x = Resources.MyResourceImage;
A full example of the code I suggest:
using System.Windows.Forms;
using Testapplication.Properties;
namespace Testapplication {
public class Class1 {
public Class1() {
Form MyForm = new Form();
ToolStrip MyToolStrip = new ToolStrip();
MyForm.Controls.Add(MyToolStrip);
ToolStripButton MyButton = new ToolStripButton();
MyToolStrip.Items.Add(MyButton);
MyButton.Image = Resources.MyResourceImage;
MyForm.Show();
}
}
}
Don't forget to add a using to YourApps' Properties namespace. Your Resources.resx (.cs) file resides in that namespace and is used to provide strong-types object references like images. In your case, replace "MyResourceImage" with "save" (omit the quotes).
ps. A glance at the most important part of my Resources.designer.cs file:
internal static System.Drawing.Bitmap MyResourceImage {
get {
object obj = ResourceManager.GetObject("MyResourceImage", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
So you mean setting image from an embedded resource?
string res = "MyAssembly.Resources.toolStripButton9.Image";
Stream s = this.GetType().Assembly.GetManifestResourceStream( res );
Icon icon = Icon.FromStream( s );
Use Webleeuws answer if it works, way easier than this :P

Categories

Resources