利用API设置桌面背景

Posted on 2019-01-23 14:54  努力成长静待花开  阅读(1373)  评论(0编辑  收藏  举报

实现效果:

  

知识运用:

  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);  //设置桌面背景
                }
            }
        }