Accueil > > > UNE CLASSE POUR LES WALLPAPERS
UNE CLASSE POUR LES WALLPAPERS
Information sur la source
Description
Voici une classe qui vous permettra de gérer des affichages de fond d'écran facilement.
Source
- // Wallpaper.cs - Une classe pour afficher un fond d'écran sous Windows
- // Conçue et réalisée par Gulix
- // Contact : gulix33xp@yahoo.fr - http://gulix.free.fr
- // Pour plus d'informations, lire le fichier d'informations fourni avec la classe
-
-
- using System;
- using System.Drawing;
- using System.Collections;
- using System.ComponentModel;
- using System.Windows.Forms;
- using System.Runtime.InteropServices;
- using System.IO;
- using System.Data;
- using Microsoft.Win32;
-
- public class Wallpaper
- {
- // Variables et Fonctions nécessaires à l'affichage du Wallpaper
- const int SPI_SETDESKWALLPAPER = 20;
- const int SPIF_UPDATEINIFILE = 0x01;
- const int SPIF_SENDWININICHANGE = 0x02;
- [DllImport("user32.dll", CharSet = CharSet.Auto)]
- static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
- [DllImport("user32.dll")]
- public static extern void SetSysColors(int elementCount, int[] colorNames, int[] colorValues);
-
- // Enumération permettant de fixer le style d'affichage
- public enum Affichage
- {
- centrer,
- mosaique,
- etirer,
- ajuster
- }
-
- // On déclare les membres
- private string nomfichier;
- private Affichage affichage; // Style d'affichage
- private System.Drawing.Color couleurFond; // Couleur de fond du bureau
-
- // Constructeur de la classe Wallpaper
- public Wallpaper(string fichier, Affichage affich, Color fond)
- {
- this.nomfichier = fichier;
- this.affichage = affich;
- this.couleurFond = fond;
- }
-
- // GetNomCourt
- // permet de retrouver le nom du fichier, sans son chemin complet
- public string GetNomCourt()
- {
- string[] split;
- char[] separateur ={ '\\' };
- int max;
- split = this.nomfichier.Split(separateur);
- max = split.GetUpperBound(0);
- return split[max];
- }
-
- // GetRepertoire
- // permet de retrouver le repertoire contenant l'image
- public string GetRepertoire()
- {
- string[] split;
- string[] join;
- char[] separateur ={ '\\' };
- int max;
- split = this.nomfichier.Split(separateur);
- max = split.GetUpperBound(0);
- join = new string[max];
- for (int i = 0; i < (max); i++)
- {
- join[i] = split[i];
- }
- return String.Join("\\", join) + "\\";
- }
-
-
- // GetImageHauteur
- // permet d'obtenir la hauteur du fichier image, en pixels
- public int GetImageHauteur()
- {
- int retour = 0;
- try
- {
- Image image = new Bitmap(this.nomfichier);
- retour = image.Height;
- }
- catch
- {
- retour = -1;
- }
- return retour;
- }
-
- // GetImageLargeur
- // permet d'obtenir la largeur du fichier image, en pixels
- public int GetImageLargeur()
- {
- int retour = 0;
- try
- {
- Image image = new Bitmap(this.nomfichier);
- retour = image.Width;
- }
- catch
- {
- retour = -1;
- }
- return retour;
- }
-
- // Afficher
- // Affiche le fond d'écran suivant les paramètres fournis
- public void Afficher()
- {
- try
- {
- // On recopie l'image dans les fichiers temporaires au format bitmap
- System.Drawing.Image image;
- if (this.affichage == Affichage.ajuster)
- {
- image = System.Drawing.Image.FromFile(this.Ajustement());
- }
- else
- {
- image = System.Drawing.Image.FromFile(this.GetRepertoire() + this.GetNomCourt());
- }
- string fichierTemporaire = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
- image.Save(fichierTemporaire, System.Drawing.Imaging.ImageFormat.Bmp);
-
- // On modifie le style d'affichage dans la base de registre
- RegistryKey cle = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
- if (this.affichage == Affichage.etirer)
- {
- cle.SetValue(@"WallpaperStyle", 2.ToString());
- cle.SetValue(@"TileWallpaper", 0.ToString());
- }
-
- if (this.affichage == Affichage.centrer)
- {
- cle.SetValue(@"WallpaperStyle", 1.ToString());
- cle.SetValue(@"TileWallpaper", 0.ToString());
- }
-
- if (this.affichage == Affichage.mosaique)
- {
- cle.SetValue(@"WallpaperStyle", 1.ToString());
- cle.SetValue(@"TileWallpaper", 1.ToString());
- }
-
- if (this.affichage == Affichage.ajuster)
- {
- cle.SetValue(@"WallpaperStyle", 1.ToString());
- cle.SetValue(@"TileWallpaper", 0.ToString());
- }
-
- // On utilise les fonctions de la DLL user32 pour afficher le wallpaper
- SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, fichierTemporaire, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
- int[] elementArray = { 1 };
- int[] elementValues = { ColorTranslator.ToWin32(this.GetCouleurFond()) };
- // et modifier la couleur de fond du bureau
- SetSysColors(1, elementArray, elementValues);
- }
- catch
- {
- MessageBox.Show("Une erreur s'est produite lors de l'affichage du Wallpaper");
- }
- }
-
- // GetEcranLargeur
- // permet d'obtenir la largeur de l'écran
- public static int GetEcranLargeur()
- {
- return System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
- }
-
- // GetEcranHauteur
- // permet d'obtenir la hauteur de l'écran
- public static int GetEcranHauteur()
- {
- return System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
- }
-
- // Ajustement
- // Réalise l'ajustement de l'image si nécessaire
- // retourne le chemin vers le fichier ajusté
- private string Ajustement()
- {
- string fichierRetour;
- if ((this.GetImageHauteur() <= GetEcranHauteur()) && (this.GetImageLargeur() <= GetEcranLargeur()))
- {
- // Pas d'ajustement nécessaire, on retourne le nom du fichier original
- fichierRetour = this.nomfichier;
- }
- else
- {
- // On calcule les nouvelles dimensions
- double ratio = ((double)GetEcranHauteur()) / ((double)this.GetImageHauteur());
- if (ratio > (((double)GetEcranLargeur()) / ((double)this.GetImageLargeur())))
- {
- ratio = ((double)GetEcranLargeur()) / ((double)this.GetImageLargeur());
- }
- int nouvelleLargeur = (int)(((double)this.GetImageLargeur()) * ratio);
- int nouvelleHauteur = (int)(((double)this.GetImageHauteur()) * ratio);
-
- // On crée le support de la nouvelle image
- System.Drawing.Size tailleAjuster = new Size(nouvelleLargeur, nouvelleHauteur);
- System.Drawing.Image imageAjuster = null;
-
- // On crée la nouvelle image à partir de l'original, et de la nouvelle taille
- imageAjuster = new Bitmap(Image.FromFile(this.nomfichier), tailleAjuster);
- imageAjuster.Save(Path.Combine(Path.GetTempPath(), "ajuster.bmp"), System.Drawing.Imaging.ImageFormat.Bmp);
- imageAjuster.Dispose();
- fichierRetour = Path.Combine(Path.GetTempPath(), "ajuster.bmp");
- }
- return fichierRetour;
- }
-
- // Méthodes d'accès aux paramètres
- // permet de limiter l'accès aux paramètres
- public Affichage GetAffichage()
- {
- return this.affichage;
- }
- public void SetAffichage(Affichage aff)
- {
- this.affichage = aff;
- }
- public Color GetCouleurFond()
- {
- return this.couleurFond;
- }
- public void SetCouleurFond(Color col)
- {
- this.couleurFond = col;
- }
-
- public override string ToString()
- {
- return this.GetNomCourt();
- }
-
- }
// Wallpaper.cs - Une classe pour afficher un fond d'écran sous Windows
// Conçue et réalisée par Gulix
// Contact : gulix33xp@yahoo.fr - http://gulix.free.fr
// Pour plus d'informations, lire le fichier d'informations fourni avec la classe
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using System.Data;
using Microsoft.Win32;
public class Wallpaper
{
// Variables et Fonctions nécessaires à l'affichage du Wallpaper
const int SPI_SETDESKWALLPAPER = 20;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDWININICHANGE = 0x02;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
[DllImport("user32.dll")]
public static extern void SetSysColors(int elementCount, int[] colorNames, int[] colorValues);
// Enumération permettant de fixer le style d'affichage
public enum Affichage
{
centrer,
mosaique,
etirer,
ajuster
}
// On déclare les membres
private string nomfichier;
private Affichage affichage; // Style d'affichage
private System.Drawing.Color couleurFond; // Couleur de fond du bureau
// Constructeur de la classe Wallpaper
public Wallpaper(string fichier, Affichage affich, Color fond)
{
this.nomfichier = fichier;
this.affichage = affich;
this.couleurFond = fond;
}
// GetNomCourt
// permet de retrouver le nom du fichier, sans son chemin complet
public string GetNomCourt()
{
string[] split;
char[] separateur ={ '\\' };
int max;
split = this.nomfichier.Split(separateur);
max = split.GetUpperBound(0);
return split[max];
}
// GetRepertoire
// permet de retrouver le repertoire contenant l'image
public string GetRepertoire()
{
string[] split;
string[] join;
char[] separateur ={ '\\' };
int max;
split = this.nomfichier.Split(separateur);
max = split.GetUpperBound(0);
join = new string[max];
for (int i = 0; i < (max); i++)
{
join[i] = split[i];
}
return String.Join("\\", join) + "\\";
}
// GetImageHauteur
// permet d'obtenir la hauteur du fichier image, en pixels
public int GetImageHauteur()
{
int retour = 0;
try
{
Image image = new Bitmap(this.nomfichier);
retour = image.Height;
}
catch
{
retour = -1;
}
return retour;
}
// GetImageLargeur
// permet d'obtenir la largeur du fichier image, en pixels
public int GetImageLargeur()
{
int retour = 0;
try
{
Image image = new Bitmap(this.nomfichier);
retour = image.Width;
}
catch
{
retour = -1;
}
return retour;
}
// Afficher
// Affiche le fond d'écran suivant les paramètres fournis
public void Afficher()
{
try
{
// On recopie l'image dans les fichiers temporaires au format bitmap
System.Drawing.Image image;
if (this.affichage == Affichage.ajuster)
{
image = System.Drawing.Image.FromFile(this.Ajustement());
}
else
{
image = System.Drawing.Image.FromFile(this.GetRepertoire() + this.GetNomCourt());
}
string fichierTemporaire = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
image.Save(fichierTemporaire, System.Drawing.Imaging.ImageFormat.Bmp);
// On modifie le style d'affichage dans la base de registre
RegistryKey cle = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
if (this.affichage == Affichage.etirer)
{
cle.SetValue(@"WallpaperStyle", 2.ToString());
cle.SetValue(@"TileWallpaper", 0.ToString());
}
if (this.affichage == Affichage.centrer)
{
cle.SetValue(@"WallpaperStyle", 1.ToString());
cle.SetValue(@"TileWallpaper", 0.ToString());
}
if (this.affichage == Affichage.mosaique)
{
cle.SetValue(@"WallpaperStyle", 1.ToString());
cle.SetValue(@"TileWallpaper", 1.ToString());
}
if (this.affichage == Affichage.ajuster)
{
cle.SetValue(@"WallpaperStyle", 1.ToString());
cle.SetValue(@"TileWallpaper", 0.ToString());
}
// On utilise les fonctions de la DLL user32 pour afficher le wallpaper
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, fichierTemporaire, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
int[] elementArray = { 1 };
int[] elementValues = { ColorTranslator.ToWin32(this.GetCouleurFond()) };
// et modifier la couleur de fond du bureau
SetSysColors(1, elementArray, elementValues);
}
catch
{
MessageBox.Show("Une erreur s'est produite lors de l'affichage du Wallpaper");
}
}
// GetEcranLargeur
// permet d'obtenir la largeur de l'écran
public static int GetEcranLargeur()
{
return System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
}
// GetEcranHauteur
// permet d'obtenir la hauteur de l'écran
public static int GetEcranHauteur()
{
return System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
}
// Ajustement
// Réalise l'ajustement de l'image si nécessaire
// retourne le chemin vers le fichier ajusté
private string Ajustement()
{
string fichierRetour;
if ((this.GetImageHauteur() <= GetEcranHauteur()) && (this.GetImageLargeur() <= GetEcranLargeur()))
{
// Pas d'ajustement nécessaire, on retourne le nom du fichier original
fichierRetour = this.nomfichier;
}
else
{
// On calcule les nouvelles dimensions
double ratio = ((double)GetEcranHauteur()) / ((double)this.GetImageHauteur());
if (ratio > (((double)GetEcranLargeur()) / ((double)this.GetImageLargeur())))
{
ratio = ((double)GetEcranLargeur()) / ((double)this.GetImageLargeur());
}
int nouvelleLargeur = (int)(((double)this.GetImageLargeur()) * ratio);
int nouvelleHauteur = (int)(((double)this.GetImageHauteur()) * ratio);
// On crée le support de la nouvelle image
System.Drawing.Size tailleAjuster = new Size(nouvelleLargeur, nouvelleHauteur);
System.Drawing.Image imageAjuster = null;
// On crée la nouvelle image à partir de l'original, et de la nouvelle taille
imageAjuster = new Bitmap(Image.FromFile(this.nomfichier), tailleAjuster);
imageAjuster.Save(Path.Combine(Path.GetTempPath(), "ajuster.bmp"), System.Drawing.Imaging.ImageFormat.Bmp);
imageAjuster.Dispose();
fichierRetour = Path.Combine(Path.GetTempPath(), "ajuster.bmp");
}
return fichierRetour;
}
// Méthodes d'accès aux paramètres
// permet de limiter l'accès aux paramètres
public Affichage GetAffichage()
{
return this.affichage;
}
public void SetAffichage(Affichage aff)
{
this.affichage = aff;
}
public Color GetCouleurFond()
{
return this.couleurFond;
}
public void SetCouleurFond(Color col)
{
this.couleurFond = col;
}
public override string ToString()
{
return this.GetNomCourt();
}
}
Conclusion
Dans le zip, vous trouverez, en plus de la classe, un fichier txt qui explique rapidement comment utiliser la classe. Dans le courant de la semaine, je devrais vous présenter une application assez complète utilisant cette classe.
Historique
- 10 janvier 2005 15:27:45 :
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
"fond d'ecran" [ par cudenetf ]
bonjour,j'aimerais si possible avoir un logo en fond d'ecran quelque soit le formulaire (ou control qui passe dessus)en fait j'aimerais que ce soit t
[Classes] Attributs [ par stailer ]
Bonjour tout le monde, dans une classe on peut définir des attributs très simplement comme ceci : [Description("Fond d'écran")] private Image fo
Capture d'Ecran [ par fdouieb ]
Bonjour,a l'adresse suivante :http://www.csharpfr.com/forum.v2.aspx?ID=260557il y a la possibilité de faire des captures d'ecran.cela fonctionne bien
Treeview C#(mettre une image en fond) [ par trioy ]
Hello,Petite question, après avoir cherché, sans résultat... y'a t il qelqu'un qui sait comment on fait pour mettre une image en arrière plan dans un
[C#] Modifier la couleur d'arrière fond de ComboBox et checkBox [ par bibicool ]
Bonjour à tous, J'aimerais modifier la couleur d'arrière fond de ComboBox et de CheckBox lorsque ceux-ci sont Disabled (Enabled = false).
Dimension de l'ecran [ par manou2005 ]
Bonjour tout le monde, je voudrais savoir comment faire pour avoir les dimensions de l'écran en C#.Et merci.
Dimension de mon image de fond de ma frame [ par oxboz ]
Bonjour, Voila j'ai une image à mettre en image de fond de toutes mes frames. Probleme: Celles ci sont de dimensions différentes. Comment f
listbox et image de fond [C#] [ par emachede ]
bonjour je voudrais simplement placer une image jpg dans le fond de ma listbox (vu que j'arrive pas à la rendre transparente, je ruse) j'ai essa
DirectX (D3D) transparence [ par clemox ]
Bonsoir :) Ceux qui fond du directX ont pu se rendre compte que directdraw va bientôt disparaître du SDK ... C'est pourtant bien prat
Double Buffering [ par emmanuel9 ]
Bonjour à tous, En faite j'ai un panel avec un fond blanc et je voudrais faire bouger un carré noir dessus avec les touches sans que ca sc
|
Derniers Blogs
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|