How to save a Forms Background Image using My.Sett

2019-02-21 07:17发布

问题:

I'm trying to make an Operating System in Visual Basic (program based of course) and it needs personalisation.

I want the user to be able to choose from a select group of images, stored in the Resources of the project, and I want that image to be saved, so that the next time they log on to the software, the form has the same image they selected saved.

Extra Information:

The image selection is on a seperate form. Using:

If ComboBox1.Text = "Beach Fade" Then
    PictureBox1.BackgroundImage = My.Resources.beach_fade
End If

Main Desktop form uses the "Background image" to have the image selected.

回答1:

Use My.Settings to persist user settings.

This is the code I used to demo it. I have a form with ComboBox1 and PictureBox1. With this code, you can have your image selection persist.

Go into your project properties and click the Settings option on the left. Create a setting called BackgroundImageName of type String. You can choose if the scope is saved per-user or per-application.

Then in project properties go to Resources and add two images named "beach_fade" and "mountain_fade". You know how to do this

Then paste this code

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.ComboBox1.Items.Add("Beach Fade")
        Me.ComboBox1.Items.Add("Mountain Fade")
        Me.ComboBox1.Text = My.Settings.BackgroundImageName
        setBackgroundImage()
    End Sub

    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        My.Settings.BackgroundImageName = Me.ComboBox1.Text
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        setBackgroundImage()
    End Sub

    Private Sub setBackgroundImage()
        If ComboBox1.Text = "Beach Fade" Then
            PictureBox1.BackgroundImage = My.Resources.beach_fade
        ElseIf ComboBox1.Text = "Mountain Fade" Then
            PictureBox1.BackgroundImage = My.Resources.mountain_fade
        End If
    End Sub

End Class

The application will start up every time with the image selected in the ComboBox before last close.