Comparing two images from the clipboard class - c#

In a C# winform app. I'm writing a Clipboard log manager that logs text to a log file, (everytime a Ctrl+c/x is pressed the copied/cut text gets appended to the file)
I also did the same for images, that is, if you press "prtScreen", the screen shot you took will also go to a folder.
I do that by using a timer, inside I have something which 'looks' like this:
if (Clipboard.ContainsImage())
{
if (IsClipboardUpdated())
{
LogData();
UpdateLastClipboardData();
}
}
This is how the rest of the methods look like:
public void UpdateLastClipboardData()
{
// ... other updates
LastClipboardImage = Clipboard.GetImage();
}
// This is how I determine if there's a new image in the clipboard...
public bool IsClipboardUpdated()
{
return (LastClipboardImage != Clipboard.GetImage());
}
public void LogData()
{
Clipboard.GetImage().Save(ImagesLogFolder + "\\Image" + now_hours + "_" + now_mins + "_" + now_secs + ".jpg");
}
The problem is: inside the update method, "LastClipboardImage != Clipboard.GetImage()" is always returning true!
I even did the following inside the update method:
Image img1 = Clipboard.GetImage();
Image img2 = Clipboard.GetImage();
Image img3 = img2;
bool b1 = img1 == img2; // this returned false. WHY??
bool b2 = img3 == img2; // this returned true. Makes sense.
Please help, the comparison isn't working... why?

A little test. Call two times the GetImage method for the same image
void Main()
{
Image bmp1 = Clipboard.GetImage();
Image bmp2 = Clipboard.GetImage();
if(bmp1 != null && bmp1 == bmp2)
Console.WriteLine("True");
else
Console.WriteLine("False");
}
it returns always false. So every time you call Clipboard.GetImage() you get a different image instance and thus you cannot compare then using a simple == operator
You are comparing two different instances of an Image object and of course they are not the same.
If you really want to compare the image down to the pixel level you need a more invasive (and performance hungry method) like this
bool ImagesAreDifferent(Image img1, Image img2)
{
Bitmap bmp1 = new Bitmap(img1);
Bitmap bmp2 = new Bitmap(img2);
bool different = false;
if (bmp1.Width == bmp2.Width && bmp1.Height == bmp2.Height)
{
for (int i = 0; i < bmp1.Width; i++)
{
for (int j = 0; j < bmp1.Height; j++)
{
Color col1 = bmp1.GetPixel(i, j);
Color col2 = bmp2.GetPixel(i, j);
if (col1 != col2)
{
i = bmp1.Width + 1;
different = true;
break;
}
}
}
}
return different;
}
Notice how this is possible because the Color structure defines an Equality operator that checks if the color RGB values are the same between two colors

Image checks equality with the Object.equals, which tests for reference equality with reference types, not semantic equality. This is why img2 == img3 is true, as you have previously copied img2's reference into img3. However, for img1 and img2, you called Clipboard.GetImage which constructs a new image object.
If you actually want to test if two image objects contain the same data, you will need to write your own method - perhaps an extension method if you don't want to subclass Image.
public static class ImageExtensions
{
public static bool MyEquals(this Image x, Image y)
{
// compute and return your definition of equality here
}
}
Note that the == operator will not call this method automatically, and you will have to check equality with Image.MyEquals.

I think rather than comparing images you can change the program logic to overcome this problem.
How about capture event of new item added to clipboard and write in to log?
you can try code sample code from below link
http://www.codeproject.com/Tips/467361/Using-Clipboard-Csharp-4-0-Wrapper-inside
// Use the "ClipboardManager" to manage in a more comprehensive the clipboard
// I assume that "this" is a Form
ClipboardManager manager = new ClipboardManager(this);
// Use "All" to handle all kinds of objects from the clipboard
// otherwise use "Files", "Image" or "Text"
manager.Type = ClipboardManager.CheckType.All;
// Use events to manage the objects in the clipboard
manager.OnNewFilesFound += (sender, eventArg) =>
{
foreach (String item in eventArg)
{
Console.WriteLine("New file found in clipboard : {0}", item);
}
};
manager.OnNewImageFound += (sender, eventArg) =>
{
Console.WriteLine("New image found in clipboard -> Width: {0} , Height: {1}",
eventArg.Width, eventArg.Height);
};
manager.OnNewTextFound += (sender, eventArg) =>
{
Console.WriteLine("New text found in clipboard : {0}", eventArg);
};
// Use the method "StartChecking" to start capturing objects in the clipboard
manager.StartChecking();
// Close the capturing
manager.Dispose();

Related

How to make an enum-like Unity inspector drop-down menu from a string array with C#?

I'm making a Unity C# script that is meant to be used by other people as a character dialog tool to write out conversations between multiple game characters.
I have a DialogueElement class and then I create a list of DialogueElement objects. Each object represents a line of dialogue.
[System.Serializable] //needed to make ScriptableObject out of this class
public class DialogueElement
{
public enum Characters {CharacterA, CharacterB};
public Characters Character; //Which characters is saying the line of dialog
public string DialogueText; //What the character is saying
}
public class Dialogue : ScriptableObject
{
public string[] CharactersList; //defined by the user in the Unity inspector
public List<DialogueElement> DialogueItems; //each element represents a line of dialogue
}
I want the user to be able to use the dialog tool by only interacting with the Unity inspector (so no editing code). The problem with this setup then is that the user of the dialogue tool cannot specify their own custom names (such as Felix or Wendy) for the characters in the Characters enum since they are hardcoded as "CharacterA" and "CharacterB" in the DialogueElement class.
For those not familiar with Unity, it is a game creation program. Unity lets users create physical files (known as scriptable objects) that acts as containers for class objects. The public variables of the scriptable object can be defined through a visual interface called the "inspector" as you can see below:
I want to use an enum to specify which characters is the one saying the line of dialog because using an enum creates a nice drop-down menu in the inspector where the user can easily select the character without having to manually type the name of the character for each line of dialogue.
How can I allow the user to define the elements of the Characters enum? In this case I was trying to use a string array variable where the player can type the name of all the possible characters and then use that array to define the enum.
I don't know if solving the problem this way is possible. I'm open to ANY ideas that will allow the user to specify a list of names that can then be used to create a drop down menu in the inspector where the user selects one of the names as seen in the image above.
The solution doesn't need to specifically declare a new enum from a string array. I just want to find a way to make this work. One solution I thought of is to write a separate script that would edit the text of the C# script that contains the Character enum. I think this would technically work since Unity automatically recompiles scripts every time it detects they were changed and updates the scriptable objects in the inspector, but I was hoping to find a cleaner way.
Link to repository for reference:
https://github.com/guitarjorge24/DialogueTool
You can't change the enum itself as it needs to be compiled (well it is not completely impossible but I wouldn't recommend to go ways like actively change a script and force a re-compile)
Without seeing the rest of the types you need it is a bit hard but what you want you would best do in a custom editor script using EditorGUILayout.Popup. As said I don't know your exact needs and the type Characters or how exactly you reference them so for now I will assume you reference your DialogueElement to a certain character via its index in the list Dialogue.CharactersList. This basically works like an enum then!
Since these editor scripts can get quite complex I try to comment every step:
using System;
using System.Collections.Generic;
using System.Linq;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
#endif
using UnityEngine;
[CreateAssetMenu]
public class Dialogue : ScriptableObject
{
public string[] CharactersList;
public List<DialogueElement> DialogueItems;
}
[Serializable] //needed to make ScriptableObject out of this class
public class DialogueElement
{
// You would only store an index to the according character
// Since I don't have your Characters type for now lets reference them via the Dialogue.CharactersList
public int CharacterID;
//public Characters Character;
// By using the attribute [TextArea] this creates a nice multi-line text are field
// You could further configure it with a min and max line size if you want: [TextArea(minLines, maxLines)]
[TextArea] public string DialogueText;
}
// This needs to be either wrapped by #if UNITY_EDITOR
// or placed in a folder called "Editor"
#if UNITY_EDITOR
[CustomEditor(typeof(Dialogue))]
public class DialogueEditor : Editor
{
// This will be the serialized clone property of Dialogue.CharacterList
private SerializedProperty CharactersList;
// This will be the serialized clone property of Dialogue.DialogueItems
private SerializedProperty DialogueItems;
// This is a little bonus from my side!
// These Lists are extremely more powerful then the default presentation of lists!
// you can/have to implement completely custom behavior of how to display and edit
// the list elements
private ReorderableList charactersList;
private ReorderableList dialogItemsList;
// Reference to the actual Dialogue instance this Inspector belongs to
private Dialogue dialogue;
// class field for storing available options
private GuiContent[] availableOptions;
// Called when the Inspector is opened / ScriptableObject is selected
private void OnEnable()
{
// Get the target as the type you are actually using
dialogue = (Dialogue) target;
// Link in serialized fields to their according SerializedProperties
CharactersList = serializedObject.FindProperty(nameof(Dialogue.CharactersList));
DialogueItems = serializedObject.FindProperty(nameof(Dialogue.DialogueItems));
// Setup and configure the charactersList we will use to display the content of the CharactersList
// in a nicer way
charactersList = new ReorderableList(serializedObject, CharactersList)
{
displayAdd = true,
displayRemove = true,
draggable = false, // for now disable reorder feature since we later go by index!
// As the header we simply want to see the usual display name of the CharactersList
drawHeaderCallback = rect => EditorGUI.LabelField(rect, CharactersList.displayName),
// How shall elements be displayed
drawElementCallback = (rect, index, focused, active) =>
{
// get the current element's SerializedProperty
var element = CharactersList.GetArrayElementAtIndex(index);
// Get all characters as string[]
var availableIDs = dialogue.CharactersList;
// store the original GUI.color
var color = GUI.color;
// Tint the field in red for invalid values
// either because it is empty or a duplicate
if(string.IsNullOrWhiteSpace(element.stringValue) || availableIDs.Count(item => string.Equals(item, element.stringValue)) > 1)
{
GUI.color = Color.red;
}
// Draw the property which automatically will select the correct drawer -> a single line text field
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUI.GetPropertyHeight(element)), element);
// reset to the default color
GUI.color = color;
// If the value is invalid draw a HelpBox to explain why it is invalid
if (string.IsNullOrWhiteSpace(element.stringValue))
{
rect.y += EditorGUI.GetPropertyHeight(element);
EditorGUI.HelpBox(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), "ID may not be empty!", MessageType.Error );
}else if (availableIDs.Count(item => string.Equals(item, element.stringValue)) > 1)
{
rect.y += EditorGUI.GetPropertyHeight(element);
EditorGUI.HelpBox(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), "Duplicate! ID has to be unique!", MessageType.Error );
}
},
// Get the correct display height of elements in the list
// according to their values
// in this case e.g. dependent whether a HelpBox is displayed or not
elementHeightCallback = index =>
{
var element = CharactersList.GetArrayElementAtIndex(index);
var availableIDs = dialogue.CharactersList;
var height = EditorGUI.GetPropertyHeight(element);
if (string.IsNullOrWhiteSpace(element.stringValue) || availableIDs.Count(item => string.Equals(item, element.stringValue)) > 1)
{
height += EditorGUIUtility.singleLineHeight;
}
return height;
},
// Overwrite what shall be done when an element is added via the +
// Reset all values to the defaults for new added elements
// By default Unity would clone the values from the last or selected element otherwise
onAddCallback = list =>
{
// This adds the new element but copies all values of the select or last element in the list
list.serializedProperty.arraySize++;
var newElement = list.serializedProperty.GetArrayElementAtIndex(list.serializedProperty.arraySize - 1);
newElement.stringValue = "";
}
};
// Setup and configure the dialogItemsList we will use to display the content of the DialogueItems
// in a nicer way
dialogItemsList = new ReorderableList(serializedObject, DialogueItems)
{
displayAdd = true,
displayRemove = true,
draggable = true, // for the dialogue items we can allow re-ordering
// As the header we simply want to see the usual display name of the DialogueItems
drawHeaderCallback = rect => EditorGUI.LabelField(rect, DialogueItems.displayName),
// How shall elements be displayed
drawElementCallback = (rect, index, focused, active) =>
{
// get the current element's SerializedProperty
var element = DialogueItems.GetArrayElementAtIndex(index);
// Get the nested property fields of the DialogueElement class
var character = element.FindPropertyRelative(nameof(DialogueElement.CharacterID));
var text = element.FindPropertyRelative(nameof(DialogueElement.DialogueText));
var popUpHeight = EditorGUI.GetPropertyHeight(character);
// store the original GUI.color
var color = GUI.color;
// if the value is invalid tint the next field red
if(character.intValue < 0) GUI.color = Color.red;
// Draw the Popup so you can select from the existing character names
character.intValue = EditorGUI.Popup(new Rect(rect.x, rect.y, rect.width, popUpHeight), new GUIContent(character.displayName), character.intValue, availableOptions);
// reset the GUI.color
GUI.color = color;
rect.y += popUpHeight;
// Draw the text field
// since we use a PropertyField it will automatically recognize that this field is tagged [TextArea]
// and will choose the correct drawer accordingly
var textHeight = EditorGUI.GetPropertyHeight(text);
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, textHeight), text);
},
// Get the correct display height of elements in the list
// according to their values
// in this case e.g. we add an additional line as a little spacing between elements
elementHeightCallback = index =>
{
var element = DialogueItems.GetArrayElementAtIndex(index);
var character = element.FindPropertyRelative(nameof(DialogueElement.CharacterID));
var text = element.FindPropertyRelative(nameof(DialogueElement.DialogueText));
return EditorGUI.GetPropertyHeight(character) + EditorGUI.GetPropertyHeight(text) + EditorGUIUtility.singleLineHeight;
},
// Overwrite what shall be done when an element is added via the +
// Reset all values to the defaults for new added elements
// By default Unity would clone the values from the last or selected element otherwise
onAddCallback = list =>
{
// This adds the new element but copies all values of the select or last element in the list
list.serializedProperty.arraySize++;
var newElement = list.serializedProperty.GetArrayElementAtIndex(list.serializedProperty.arraySize - 1);
var character = newElement.FindPropertyRelative(nameof(DialogueElement.CharacterID));
var text = newElement.FindPropertyRelative(nameof(DialogueElement.DialogueText));
character.intValue = -1;
text.stringValue = "";
}
};
// Get the existing character names ONCE as GuiContent[]
// Later only update this if the charcterList was changed
availableOptions = dialogue.CharactersList.Select(item => new GUIContent(item)).ToArray();
}
public override void OnInspectorGUI()
{
DrawScriptField();
// load real target values into SerializedProperties
serializedObject.Update();
EditorGUI.BeginChangeCheck();
charactersList.DoLayoutList();
if(EditorGUI.EndChangeCheck())
{
// Write back changed values into the real target
serializedObject.ApplyModifiedProperties();
// Update the existing character names as GuiContent[]
availableOptions = dialogue.CharactersList.Select(item => new GUIContent(item)).ToArray();
}
dialogItemsList.DoLayoutList();
// Write back changed values into the real target
serializedObject.ApplyModifiedProperties();
}
private void DrawScriptField()
{
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.ObjectField("Script", MonoScript.FromScriptableObject((Dialogue)target), typeof(Dialogue), false);
EditorGUI.EndDisabledGroup();
EditorGUILayout.Space();
}
}
#endif
And this is how it would look like now
Another option is to use an inspector enhancement asset like Odin Inspector or NaughtyAttributes.
So if you had this member:
public string[] CharactersList;
With Odin you would write:
[ValueDropdown("CharactersList")]
In NaughtyAttributes you would write:
[Dropdown("CharactersList")]
These solutions are similar to the suggestion by datsfain.
Although Odin is not free, it has tons of fancy extra functionality.
https://odininspector.com/attributes/value-dropdown-attribute
NaughtyAttributes is free but a bit older and more basic.
https://dbrizov.github.io/na-docs/attributes/drawer_attributes/dropdown.html
I'm going to write another answer... because double answers are better!
As derHugo said in his answer, it could be done using enums, but it would force a recompile. Well, sometimes maybe you just really want that enum (they are much faster than strings in some scenarios) and you're willing to accept the recompilation penalty.
So here's a little utility class I wrote for generating an enum and saving it to file.
Make a member variable with a list of strings that the designer can edit.
You'll probably want to put a button on your UI called "GenerateEnums" or something like that and perhaps a string for the save directory, which would call the save function and write the enum definition to file. There is code to force a recompile, so whenever the designer presses that button, they'll need to wait for a few seconds. Also, there is the chicken-and-egg problem - you can't reference the type until the definition has been generated at least once. Typically I get around that by just putting a file with the same filename in the intended location and giving it a dummy enum (like "public enum CharacterType { dummy }"). After the designer edits the string list, presses the generate button, and waits for a few seconds, they'll be able to see the updated selections in any fields that use that enum type (CharacterType in this example).
// this has a bunch of functions for generating enums in the editor
using System.Collections.Generic;
public static class EnumUtils
{
private static readonly HashSet<string> m_keywords = new HashSet<string> {
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked",
"class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else",
"enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for",
"foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock",
"long", "namespace", "new", "null", "object", "operator", "out", "override", "params",
"private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed",
"short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw",
"true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using",
"virtual", "void", "volatile", "while"
};
// This function will return a string containing an enum declaration with the specified parameters.
// name --> the name of the enum to create
// values -> the enum values
// primitive --> byte, int, uint, short, int64, etc (empty string means no type specifier)
// makeClassSize --> if this is true, an extra line will be added that makes a static class to hold the size.
// example:
// print(MakeEnumDeclaration("MyType", { Option1, Option2, Option3 }, "byte", true));
// output --> public enum MyType : byte { Option1, Option2, Option3 }
// public static class MyTypeSize { public const byte Size = 3; }
public static string MakeEnumDeclaration(string name, List<string> values, string primitive, bool makeSizeClass)
{
string prim = primitive.Length <= 0 ? "" : " : " + primitive;
string declaration = "public enum " + name + prim + " { ";
int countMinusOne = values.Count - 1;
for (int i = 0; i < values.Count; i++) {
declaration += MakeStringEnumCompatible(values[i]);
if (i < countMinusOne) { declaration += ", "; }
}
declaration += " }\n";
if (makeSizeClass) {
declaration += $"public static class {name}Size {{ public const {primitive} Size = {values.Count}; }}\n";
}
return declaration;
}
public static void WriteDeclarationToFile(string fileName, string declaration, bool reImport = false, string filePath = "Assets/Scripts/Generated/")
{
// ensure that the output directory exists
System.IO.Directory.CreateDirectory(filePath);
// write the file
System.IO.File.WriteAllText(filePath + fileName, "// This file was auto-generated\n\n" + declaration);
#if UNITY_EDITOR
if (reImport) { UnityEditor.AssetDatabase.ImportAsset(filePath); }
#endif
}
public static void WriteDeclarationsToFile(string fileName, List<string> declarations, bool reImport = false, string filePath = "Assets/Scripts/Generated/")
{
string text = "";
for (int i = 0; i < declarations.Count; i++) { text += declarations[i]; }
WriteDeclarationToFile(fileName, text, reImport, filePath);
}
// given a string, attempts to make the string compatible with an enum
// if there are any spaces, it will attempt to make the string camel-case
public static string MakeStringEnumCompatible(string text)
{
if (text.Length <= 0) { return "INVALID_ENUM_NAME"; }
string ret = "";
// first char must be a letter or an underscore, so ignore anything that is not
if (char.IsLetter(text[0]) || (text[0] == '_')) { ret += text[0]; }
// ignore anything that's not a digit or underscore
bool enableCapitalizeNextLetter = false;
for (int i = 1; i < text.Length; ++i) {
if (char.IsLetterOrDigit(text[i]) || (text[i] == '_')) {
if (enableCapitalizeNextLetter) {
ret += char.ToUpper(text[i]);
} else {
ret += text[i];
}
enableCapitalizeNextLetter = false;
} else if (char.IsWhiteSpace(text[i])) {
enableCapitalizeNextLetter = true;
}
}
if (ret.Length <= 0) { return "INVALID_ENUM_NAME"; }
// all the keywords are lowercase, so if we just change the first letter to uppercase,
// then there will be no conflict
if (m_keywords.Contains(ret)) { ret = char.ToUpper(ret[0]) + ret.Substring(1); }
return ret;
}
}
Caveats:
Keep in mind that this method is a bit brittle as with anytime you use an enum in the editor. Deleting or inserting an enum value in the middle of the values could cause any fields using that enum to use the wrong index because all the indexes will shift by one. There will be no compiler error and you could get weird activity at runtime.
Deleting or renaming an enum value might cause your code to stop compiling if you're using that enum value in your code (which is probably a good thing - with strings there is no compiler error and you'll get a silent confusing surprise at runtime).
For those who need enum like string dropdown, You can use code from my github repo.
download this folder and add it in your project.
https://github.com/datsfain/EditorCools/tree/main/Assets/EditorCools/DropdownStringAttribute
add following lines of code to any serializable class:
[Dropdown(nameof(MethodThatReturnsStringArray))]
public string options2;

How to resize images efficiently in C#?

I was searching for around 4 months in order to solve image-flicker problem for my 180 controls, (similar to image-boxes) which are inserted into a flow-layout-panel.
I nearly tried everything (Enabling double flicker and so on...) and nothing worked for me. But, today I figured a solution and that's by setting image size-mode to normal instead of zoom or to resize my images to fit exactly into those controls similar to picture-boxes. So I chose the second option and here is my code:
public MovieControl(Movies M1, bool show, MainForm current)
{
InitializeComponent();
Current = current;
if (M1.movie_Banner == "") bunifuImageButton1.Image = Properties.Resources.no_image_available;
else
{
WebClient client = new WebClient();
Stream stream = client.OpenRead(M1.movie_Banner);
Bitmap bitmap; bitmap = new Bitmap(stream);
if (bitmap != null)
bunifuImageButton1.Image = new Bitmap((Image)bitmap, new Size(139, 208));
stream.Flush();
stream.Close();
client.Dispose();
}
bunifuImageButton1.Tag = M1;
M1 = null;
}
Also, I want to mention that this code is being called by a thread using the following lines:
private void RunMoviesThread()
{
ClearMovies();
LoadMoviesThread = new Thread(() => LoadMoviesControls());
LoadMoviesThread.Start();
}
private void LoadMoviesControls()
{
int x = 1;
if (MPageDropDown.InvokeRequired)
this.Invoke((MethodInvoker)delegate { if (MPageDropDown.SelectedItem != null) x = int.Parse(MPageDropDown.SelectedItem.ToString()); });
else if (MPageDropDown.SelectedItem != null) x = int.Parse(MPageDropDown.SelectedItem.ToString());
for (int i = (x - 1) * Max; i < MoviesList.Count() && i < x * Max; i++)
{
MovieControl tmp = new MovieControl(MoviesList[i], ShowMError, this);
if (tmp.InvokeRequired || MoviesFlowPanel.InvokeRequired)
{
MovieControl m1 = null;
try
{
m1= new MovieControl(MoviesList[i], ShowMError, this);
}
catch { }
this.Invoke((MethodInvoker)delegate { MoviesFlowPanel.Controls.Add(m1); });
}
else
MoviesFlowPanel.Controls.Add(tmp);
tmp = null;
}
}
It worked very well, instead of the fact that it took a very long time to process. for example; and image could take about half a second and up to 20 seconds in some rare cases! could you help me figure a more efficient way...
Please Note: my images are previously uploaded on the internet and this code is written in C#. Also, without the resizing process it took only few seconds to load.
**Max value is set to 180
Thanks in advance.
Well I don't know how much this will help you, but it's worth a shot. I am not entirely confident that WebClient can be parallelized like this, but a similar example appears on page 187 of Pro .NET Performance: Optimize Your C# Applications so I am going to take a leap and say that you can use WebClient from multiple threads. I have added a new method which you could just call from your UI, although it is making a check to be sure it doesn't need to be invoked. This method reads the page number and then launches the background process which will download and resize the images and then after it does all of that it will create the controls in the UI thread.
private void GetPageAndLoadControls()
{
if (MPageDropDown.InvokeRequired)
{
MPageDropDown.Invoke((MethodInvoker)(() => GetPageAndLoadControls();));
return;
}
var page = MPageDropDown.SelectedItem != null ?
int.Parse(MPageDropDown.SelectedItem.ToString()) - 1 : 0;
Task.Run(() => LoadMoviesControls(page));
}
private void LoadMoviesControls(int page)
{
var dict = new ConcurrentDictionary<string, Bitmap>();
var movies = MovieList.Skip(page * Max).Take(Max).ToList();
using (var client = new WebClient())
{
Parallel.ForEach(movies, (m) =>
{
Stream stream = null;
Bitmap bmp = null;
try
{
if (!string.IsNullOrWhitespace(m.movie_Banner)
{
stream = client.OpenRead(s);
bmp = new Bitmap(stream);
// Note: I am guessing on a key here, that maybe there is a title
// use whatever key is going to be best for your class
dict.TryAdd(m.movie_Title, new Bitmap(bmp, 139, 208));
}
else dict.TryAdd(m.movie_Title, Properties.Resources.no_image_available);
}
finally
{
bmp?.Dispose();
stream?.Dispose();
}
});
}
// Here we have to invoke because the controls have to be created on
// the UI thread. All of the other work has already been done in background
// threads using the thread pool.
MoviesFlowPanel.Invoke((MethodInvoker)() =>
{
foreach(var movie in movies)
{
Bitmap image = null;
dict.TryGetValue(movie.movie_Title, out image);
MoviesFlowPanel.Controls.Add(
new MovieControl(movie, image, ShowMError, this);
}
});
}
// Changed the constructor to now take an image as well, so you can pass in
// the already resized image
public MovieControl(Movies M1, Bitmap image, bool show, MainForm current)
{
InitializeComponent();
Current = current;
bunifuImageButton1.Image = image ?? Properties.Resources.no_image_available; // Sanity check
bunifuImageButton1.Tag = M1;
}
Edit
Something that occurred to me after writing this and thinking more about it, you did not post the code for ClearMovies(), but from the posted code I am assuming that you are disposing the previous 180 controls and creating 180 new ones. What would be better would be to use the same approach I have shown in the code above and then instead of "creating" new controls you just update the existing ones. You could add an update method to your user control that just changes the image and the Movie item that is being stored in the control. This would save the overhead of creating new controls each time which should improve the performance. You may need to call Invalidate at the end of the Update method. Not sure and since I can't really test this all out, just wanted to mention it. Also, instead of using the Tag property to hold the Movie object, I would just add a member variable to your UserControl. This would add type safety and make it clearer what is being held where.
public class MovieControl : Control
{
public Movies Movie { get; protected set; }
// Changed the constructor to now take an image as well, so you can
// pass in the already resized image
public MovieControl(Movies M1, Bitmap image, bool show, MainForm current)
{
InitializeComponent();
Current = current;
bunifuImageButton1.Image = image ?? Properties.Resources.no_image_available; // Sanity check
Movie = M1;
}
public void UpdateMovieAndImage(Movies movie, Image image)
{
// Only dispose if it isn't null and isn't the "No Image" image
if (bunifuImageButton1.Image != null
&& bunifuImageButton1.Image != Properties.Resources.no_image_available)
{
binifuImageButton1.Image.Dispose();
}
bunifuImageButton1.Image = image;
Movie = movie;
}
}

'Control.CreateGraphics()' is a method, which is not valid in the given context in C#

So I got a method which allows me to resize a label depending on the value of another one. Basically there is a label with a result and next to it is the "KB" label. Example: 30000 KB
So I've created this to methods:
public void UpdateSizeKB()
{
lblKB.Show();
lblResultKB.Width = GetLabelsSize(lblResultKB.Text);
lblKB.Left = lblResultKB.Left + lblResultKB.Width + 5;
}
public int GetLabelsSize(string text)
{
return lblResultKB.CreateGraphics.MeasureString(text, lblResultKB.Font).Width() + lblResultKB.Margin.Left + lblResultKB.Margin.Right;
}
And I will call the UpdateSizeKB() on the form. So every time the lblResultKB changes the lblKB will change it places.
But the function GetLabelsSize actually is not working very well because it displays an error on CreateGraphics called:
'Control.CreateGraphics()' is a method, which is not valid in the given context
Do you guys have any solution for this problem? Be able to make this work
You are missing a pair of parentheses after CreateGraphics:
public int GetLabelsSize(string text)
{
return (int)(lblResultKB.CreateGraphics().MeasureString(text, lblResultKB.Font).Width + lblResultKB.Margin.Left + lblResultKB.Margin.Right);
}
i.e. you'll actually have to call the CreateGraphics() method to acquire a Graphics object, not try to access an attribute of the method. :)
However, it's good practice to use an using block with Graphics objects, since they wrap unmanaged resources, so:
public int GetLabelsSize(string text)
{
using (var g = lblResultKB.CreateGraphics()) {
return (int)(g.MeasureString(text, lblResultKB.Font).Width + lblResultKB.Margin.Left + lblResultKB.Margin.Right);
}
}

Check if several files exists in a directory

I am saving a new image everytime the uploader cropped the image and I want to check every new image if it exists. I have this code:
private void pictureBox5_MouseUp(object sender, MouseEventArgs e)
{
Selecting = false;
// Copy the selected area.
SelectedArea = GetSelectedArea(pictureBox5.Image, Color.Transparent, Points);
SelectedArea.Save(#"C:\Users\User\Desktop\Gallery\image1cropped.png", ImageFormat.Png);
}
I want it to save like image2cropped, image3cropped.. and check if it exists like
if(File.Exists(#"C:\Users\User\Desktop\Gallery\image1cropped.png", ImageFormat.Png);
I want it to check like image2cropped, image3cropped.. and so on.
ideas?
If I understand : your are saving an area to a file. The first time, you save it to image1cropped.png, and then you want automaticaly use image2cropped in order to not overwrite the first file, right ?
In this case, you can use this code :
int i = 0; // set 0 to start at 1 for "image1cropped"
string freeFileName; // the final fileName that doesn't exist
// loop while file imageXcropped exists
do
{
i++;
freeFileName = #"C:\Users\User\Desktop\Gallery\image" + i + "cropped.png";
} while (File.Exists(freeFileName));
// at this point freeFileName doesn't exists, you can use it
// use : SelectedArea.Save(freeFileName, ImageFormat.Png);

C#, variable value as a part of an object name?

For example i have a player object with a list of suits of cards it has.
player.card[0] = "diamonds";
player.card[1] = "clubs";
player.card[2] = "spades";
etc...
also i have 4 hidden pictureboxes with an image of suites ( pb_spades , pb_hearts m etc. )
and another 4 pictureboxs ( pb_playerCard1 , pb_playerCard2 , etc. ) to which I have to assign an image from a hidden pb corresponding to the suit of card the player object has.
Therefor
if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }
of course, doing it all with IFs would take quite a long time... Can I somehow use variable value as a part of an objects name?
kinda
for (int i = 1; i != 5; i++)
{
pb_playerCard+'i'.Image = pb_+'player.card[i+1]'.Image;
}
I don't think that you can use a value as a part of the control name. But, one can use an aray of controls. You will have to change many declarations and initializations of your picture boxes and put them into an array, but you will be able to write more descriptive and readable code.
Create a class Suite that has all properties, like this:
class Suite {
public string Name { get; set; }
public Image Image { get; set; }
and then create a static object for each color:
public static Diamonds = new Suite { Name = "Diamonds", Image = Resources.DiamondImage };
// ...
}
Now you can use Suite.Diamonds.
Even better is to use a Flyweight pattern to avoid the static fields. You use the Flyweight to implement the Card class.
First, there's no reason to have a hidden PictureBox control just so you can use it's Image property to store an image. Just create Image objects.
You could store the images in a dictionary, indexable by name:
var cards = new Dictionary<string, Image>() {
{ "diamonds", Image.FromFile("diamonds.jpg") }
{ "clubs", Image.FromFile("clubs.jpg") }
//...
};
Then instead of this:
if ( player.card[0] == "diamonds" ) { pb_playerCard1.Image = pb_diamonds.Image; }
You would write:
pb_playerCard1.Image = images[player.card[0]];
This code is still not great (any time you see variables like foo1, foo2, foo3, you should be putting those in an array so they can be indexed by number). The next step might be to refactor the code so you have something like:
pb_playerCard[0].Image = images[player.card[0]];
Or:
pb_playerCard[0].Image = player.card[0].Image;
thanks again guys, I got it working using a List to store card suites for the player objects and a dictionary that stores image references.
Dictionary<CardType, System.Drawing.Image> newDeckImages = new Dictionary<CardType, System.Drawing.Image>();
...
newDeckImages.Add(CardType.Diamonds, pb_diamonds.Image);
newDeckImages.Add(CardType.Hearts, pb_hearts.Image);
newDeckImages.Add(CardType.Clubs, pb_clubs.Image);
newDeckImages.Add(CardType.Spades, pb_spades.Image);
...
private void showMyCards()
{
pb_termCard1.Image = newDeckImages[Terminator.cards[0]];
pb_termCard2.Image = newDeckImages[Terminator.cards[1]];
pb_termCard3.Image = newDeckImages[Terminator.cards[2]];
pb_termCard4.Image = newDeckImages[Terminator.cards[3]];
}
The main class Player and the associated enumeration should be like this:
class Player
{
public Player(int n)
{
Cards = new List(n);
}
public IList Cards { get; private set; }
}
enum CardType
{
Diamond,
Club,
Spade,
Heart
}
Another method GetPictureBox() should in the winform partial class
public PictureBox GetPictureBox(string pictureBoxName)
{
if(this.Controls.ContainsKey(pictureBoxName))
{
Control control = this.Controls[pictureBoxName];
PictureBox pictureBox;
if ((pictureBox = control as PictureBox) != null)
{
return pictureBox;
}
}
return null;
}
Use this method in the class using the player instance.
Player player = new Player(3);
player.Cards.Add(CardType.Diamond);
player.Cards.Add(CardType.Club);
player.Cards.Add(CardType.Spade);
Dictionary dictionary = new Dictionary();
dictionary.Add(CardType.Diamond, pb_diamonds);
dictionary.Add(CardType.Spade, pb_spades);
dictionary.Add(CardType.Club, pb_clubs);
dictionary.Add(CardType.Heart, pb_hearts);
Finally the assignment to the image property,
for (int i = 1; i < 5; i++)
{
string playercardPictureBoxName = string.Concat("pb_playercard", i.ToString());
PictureBox pictureBox = this.GetPictureBox(playercardPictureBoxName);
if (pictureBox != null)
{
pictureBox.Image = dictionary[player.Cards[i - 1]].Image;
}
}
No, not how you're doing it, and although similar things can be achieved with reflection, what you want here is probably closer to just using FindControl for the "pb_playerCard" part and a simple dictionary of type Dictionary<CardSuitEnum, WhateverTheTypeOfImageIs> which you can populate with the pb_diamonds.Image etc.
Apols, I don't know what type .Image holds and can't be bothered to look it up :)

Categories