Search code examples
c#winformsresourcesembedded-resourceaccessor

Randomized File (Stream) From List of Checkboxes


So this is a two part question. Moving question #2 to the top since #1 has been answered.

Question #2 - What would be an ideal method to use checkboxes from the initial instance of Form1 (that is sadly unnamed) to set what objects are allowed. I was thinking perhaps I could have a hidden form that holds variables, and use a set accessor called from Form1 on change to the checkboxes and updates the list or dictionary I call in my above mentioned function?

The first is, I have multiple images - two currently but more to come - and want to randomly use one of those each time the function is called. Currently I'm doing this:

            System.IO.Stream file;

            Random rnd = new Random(int.Parse(Guid.NewGuid().ToString().Substring(0, 8), System.Globalization.NumberStyles.HexNumber));
            int a = rnd.Next(0, 2);

            if (a == 0)  {file = thisExe.GetManifestResourceStream("QATestFileGenTools.checkFront1.bmp");}
            else if (a == 1)  {file = thisExe.GetManifestResourceStream("QATestFileGenTools.checkFront2.bmp");}
            else {file = thisExe.GetManifestResourceStream("QATestFileGenTools.checkFront2.bmp");}

The plan was the final else was to use that image as default in the future. As seen, each image will be a resource embedded in the executable. I'd like to clean this up, possibly using a dictionary or list, where I randomly get a number between 0 and list.size-1 and then set the file equal to that.

Question #1 - How can I make a list or dictionary of resource pointers and then set file to be that resource that time?

Now, currently I cannot use my checkboxes. I have two checkboxes on Form1 to reflect each of the two current images. Since there's no way to call Form1.cbImage1.Checked because the initial instance has no name/identifier, I was considering setting a global variable, which I am loathe to do. I tried setting a get accessor, but of course that runs into the same issue.

Thanks in advance!


Solution

  • For question #1:

            var dict = new Dictionary<int, string>();
            dict.Add(0, "QATestFileGenTools.checkFront1.bmp");
            dict.Add(1,"QATestFileGenTools.checkFront2.bmp");
            dict.Add(2, "QATestFileGenTools.checkFront2.bmp");
    
            Random rnd = new Random(DateTime.Now.Millisecond);
            int randomInt = rnd.Next(0, 2);
    
            string resourceName = dict[randomInt];
            System.IO.Stream file file = thisExe.GetManifestResourceStream(resourceName);
    

    Edit: changed the random seed to something simpler and probably equally effective.