利用API設置桌面背景


實現效果:

  

知識運用:

  API函數SystemParametersInfo

  

實現代碼:

        [DllImport("user32.dll", EntryPoint = "SystemParametersInfoA")]
        static extern Int32 SystemParametersInfo(Int32 uAction,Int32 uParam,string Ipvparam,Int32 fuwinIni);
        private const int SPI_SETDESKWALLPAPER = 20;
        private void 打開OToolStripButton_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)    //如果選擇了圖片    
            { 
                string[] arr=new string[3];
                string[] arrInfo = openFileDialog1.FileNames;
                foreach(string s in arrInfo)
                {
                    FileInfo finfo = new FileInfo(s);
                    arr[0] = finfo.Name;
                    arr[1] = finfo.FullName;
                    arr[2] = finfo.Extension;
                    ListViewItem lvi = new ListViewItem(arr);
                    listView1.Items.Add(lvi);
                }
            }
        }

        private void 設為桌面背景ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                string path = listView1.SelectedItems[0].SubItems[1].Text;
                string fName = path.Substring(path.LastIndexOf("\\")+1,path.LastIndexOf(".")-path.LastIndexOf("\\")-1);
                string fExten = path.Substring(path.LastIndexOf(".")+1,path.Length-path.LastIndexOf(".")-1);
                fExten = fExten.ToLower();
                if (fExten == "bmp")
                {
                    SystemParametersInfo(SPI_SETDESKWALLPAPER,0,path,1);
                }
                else 
                {
                    string sysPath = Environment.SystemDirectory;
                    string savPaht = sysPath + "\\" + fName + ".bmp";
                    if (File.Exists(savPaht))                                   //如果轉換后的文件存在
                    {
                        File.Delete(savPaht);
                        PictureBox pb = new PictureBox();
                        pb.Image = Image.FromFile(path);
                        pb.Image.Save(savPaht,ImageFormat.Bmp);                 //使用SAVE方法實現格式轉換
                    }
                    else
                    {
                        PictureBox pb = new PictureBox();
                        pb.Image = Image.FromFile(path);
                        pb.Image.Save(savPaht, ImageFormat.Bmp);
                    }
                    SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, savPaht, 1);  //設置桌面背景
                }
            }
        }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM