如何从设置加载背景图像?

时间:2017-05-07 10:32:53

标签: vb.net

在我遇到实际问题之前,我已经做了一些研究而没有任何帮助。此外,这不是this question的副本,因为他/她正在使用ComboBox,而this question正在使用一个对我无效的打开文件对话框。

这是我的问题。我正在做一个虚拟系统覆盖(有些人称之为vb.net os),对于“桌面”,我需要从应用程序设置加载背景图像。问题是我收到了这个错误:

  

System.Drawing.dll中发生未处理的'System.IO.FileNotFounfExpection'类型的预测

     

其他信息:My.Resources._2

我的代码是:

Image.FromFile(My.Settings.bgdesk.ToString)

设置如下:

Name: bgdesk | Type: string | Scope: user | Value: My.Resources._2

另外,看看我的资源:

Example of resources

如何从资源加载背景图像?

1 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题,您希望根据用户选择动态加载和保存背景图像设置;要使用的位图已包含在资源文件中:

1)创建名为Resource1.resx的资源文件
2)在此文件中插入要使用的位图(例如名为“_1”,“_ 2”) 3)在bgdesk中,让代码只保存资源名称(即“_1”,“_ 2”)
4)添加一个ComboBox cbImgList
5)添加一个按钮,在按下时设置新的BackGround图像 6)使用以下代码(根据您的需要进行调整)

Private Function GetBackGroundImgFromRes(ByRef sError As String) As Boolean

    Try

        Dim sImgName As String = My.Settings.bgdesk
        If sImgName.Trim <> "" Then
            Dim RM As Resources.ResourceManager = My.Resources.Resource1.ResourceManager
            Dim objBitmap As Object = RM.GetObject(sImgName)
            Me.BackgroundImage = DirectCast(objBitmap, Bitmap)
        End If

        Return True

    Catch ex As Exception

        sError = ex.ToString
        Return False

    End Try

End Function

Private Function SetBackGroundImg(ByRef sError As String) As Boolean

    Try

        Dim sImgName As String = ""
        Select Case cbImgList.SelectedIndex
            Case -1
                Return True
            Case 0
                sImgName = "_1"
            Case 1
                sImgName = "_2"
        End Select

        Dim RM As Resources.ResourceManager = My.Resources.Resource1.ResourceManager
        Dim objBitmap As Object = RM.GetObject(sImgName)
        Me.BackgroundImage = DirectCast(objBitmap, Bitmap)

        My.Settings.bgdesk = sImgName

        Return True

    Catch ex As Exception

        sError = ex.ToString
        Return False

    End Try

End Function

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    Dim sError As String = ""
    SetBackGroundImg(sError)

End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    cbImgList.Items.Add("_1")
    cbImgList.Items.Add("_2")

    Dim sError As String = ""
    GetBackGroundImgFromRes(sError)

End Sub