Error showing Icon in picturebox - c#

I've been using this code to show an icon in a picturebox.
Image FromIcon(Icon ico)
{
try
{
this.toolTip1.SetToolTip(pictureBox1, "The icon of the Executable");
return ico.ToBitmap();
}
catch (Exception e)
{
this.toolTip1.SetToolTip(pictureBox1, "Don't worry, it looks perfectly fine on the executable!");
MessageBox.Show(e.Message + "\r\n" + e.StackTrace);
Clipboard.SetText(e.Message + "\r\n" + e.StackTrace);
// Alternate method
return Bitmap.FromHicon(ico.Handle);
}
}
However it is showing this error.
Requested range extends past the end of the array.
at System.Runtime.InteropServices.Marshal.CopyToNative(Object source, Int32 startIndex, IntPtr destination, Int32 length)
at System.Runtime.InteropServices.Marshal.Copy(Byte[] source, Int32 startIndex, IntPtr destination, Int32 length)
at System.Drawing.Icon.ToBitmap()
Also the icon is shown in a nasty way,
That's the same icon I use for my application. What can go wrong?
That icon is 32 bit as well as the other.
If I use another icon, it works fine and no error pops up.

I know this is an old question but I recently came across the same issue so thought I would post the resolution for anyone else facing the same problem.
For me, the issue was that I was creating the ICO files from PNG image formats but the application that the files were used in targeted a .NET framework that was earlier than 4.6 (i.e. the version in which support was added for PNG frames in .ico files). See note from the Icon.ToBitmap() documentation below:
Beginning with framework version 4.6 support was added for PNG frames in .ico files. Applications that target earlier versions of the framework but are running on the 4.6 bits can opt in into the new behavior by adding the following line to the <runtime> section of the app.config file:<AppContextSwitchOverrides value="Switch.System.Drawing.DontSupportPngFramesInIcons=false" />
So once I added the above line to the app.config file it resolved the issue.

Related

IShellItemImageFactory.GetImage(): Transparency > Black with Windows11

I use the IShellItemImageFactory.GetImage API to produce thumnails from image files. After installing Windows 11 all thumbs for images with transpareny (PNGs) are drawn with black background. That looks terrible. Does anyone know, if this behaviour can be changed? Or know another method?
The code (shortened, without exception handling and releasing ressources):
public Bitmap ExtractThumbnail(string filePath, Size size)
{
SHCreateItemFromParsingName(filePath, IntPtr.Zero, typeof(IShellItemImageFactory).GUID, out IShellItemImageFactory factory);
factory.GetImage(size, SIIGBF.SIIGBF_RESIZETOFIT, out IntPtr bmp);
return Bitmap.FromHbitmap(bmp);
}
( Windows 11, VS 2022, .Net Framework 4.8 )

I am getting C++ compilation issues while compiling my project

I am trying to implement the zoom sdk and want to prevent my screen to be captured and by screen shots for this purpose they have given some functions to be placed inside the project. When I place the code inside the function I start getting some errors and when I remove then the errors are gone.
The code which need to be placed inside the project is as follows:
BOOL CALLBACK EnumWindowsCB(HWND hwnd, LPARAM lParam)
{
SetWindowDisplayAffinity(hwnd, WDA_MONITOR);
return TRUE;
}
void CZoomSDKeDotNetWrap::DisableScreenRecord() {
DWORD pid = GetCurrentProcessId();
EnumWindows(EnumWindowsCB, pid);
uint8_t* func_data = (uint8_t*)GetProcAddress(GetModuleHandle(L"user32.dll"), "SetWindowDisplayAffinity");
}
Please let me know what these errors mean and how to resolve them.
The errors are:
enter image description here
You need to add a reference to the respective library(dll) you're using in the function you're trying to put inside the library.
As seen in your code above you're trying to use standard Windows libraries. Have you tried editing your project properties then linker input options to include user32.lib?
Thank you everyone who answered. Actually it was just because I was not using user32.lib library in the project when I added the errors got removed and it started working for me.

ImageResizer worked in ConsoleApp, now does not work in ASP.NET

I have been using ImageResizer (https://imageresizing.net/) to resize Images. I wrote a console app that was resizing images in a specified directory on my disk.
The console app was working fine, but then i added my project to a ASP.NET MVC app, and it doesnt work. I didnt just move the code, i moved the whole project and just call a start method i created that is the same as my previous main from console app. I did install resizer from NuGet in my WebApp.
When my code gets to the point where i resize images, i get an error "Request is not available in this context"
This is the part where i try to resize my image:
var resize = new ResizeSettings(resizeParameters);
ImageBuilder.Current.Build(inFile, outFile, resize);
This is the stackTrace output.
at System.Web.HttpContext.get_Request()
at ImageResizer.Configuration.Performance.GlobalPerf.JobComplete(ImageBuilder builder, ImageJob job)
at ImageResizer.ImageBuilder.BuildInternal(ImageJob job)
at ImageResizer.ImageBuilder.BuildInQueue(ImageJob job, Boolean useSemaphore, Int32 maxQueuingMilliseconds, CancellationToken cancel)
at ImageResizer.ImageBuilder.Build(ImageJob job)
at ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings, Boolean disposeSource, Boolean addFileExtension)
at ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings, Boolean disposeSource)
at ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings)
at ImageOptimizerCode.ResizeAndOptimize.ResizeImage(String inFile, String outFile, String resizeParameters) in
E:\\Vermis\\ImageOptimizer\\ImageOptimizerCode\\ResizeAndOptimize.cs:line
176
If someone can point me in the right direction, on what i am doing wrong here that would be great.
Because you have to start another project (Here is MVC) you have to configure the plugin for the project. So make sure plugin configured to be start up via:
A. add <add name="PluginName" /> in <plugins /> section of web.config file
OR
B. In Application_Start method of Global.asax create an instance of the plugin
new PluginName().Install(ImageResizer.Configuration.Config.Current);
There are some code explain of how to use this plugin:
Image Resize In ASP.NET MVC Using Image Resizer
ImageResizer enables clean, clear image resizing in ASP.NET

Image Uploading in C# Emgu Open CV not working, giving an Exception every time I try and load

Trying to upload an image into my image box and keep getting an exception, that breaks the code any ideas? (Type initialized Exception). This is the first time I have used the Emgu like this
private void btnload_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
input = new Image<Bgr, byte>(ofd.FileName).Resize(500, 500,INTER.CV_INTER_CUBIC, false);
imageBox1.Image = input;
gray = input.Convert<Gray, Byte>().PyrDown().PyrUp();
}
btnSet.Enabled = true;
}
The Stack Trace surely has more info. Usually the most common problems are:
EMGU and OpenCV DLL verisons: Check if you're using the correct 32 or 64 bit DLL's version like your project.
EMGU version agains OpenCV version: Check the Stack Trace Message, you might find something saying "Unable to load DLL 'some DLL'"
If this is the case, check if the DLL's next to your EXE have the same version (number at the end of the file name)
OpenCV DLL's Missing: Do not forget to copy OpenCV DLL's to the same folder of the EXE
Hope this helps, Cheers

Solving XNA Content Loader InvalidOperationException?

I've found StackOverflow quite a helpful reference in the past, and now that I've come up against an obstacle of my own, thought I'd try posting here.
My issue is that whenever my game attempts to load a SoundEffect file, it crashes with an InvalidOperationException (detail message: an unexpected error has occurred). This game is being written on the XNA 4.0 framework, in C# with Visual Studio 2010 express as my IDE. The sound effects being loaded are all .wav files, and are added into the game's Content project.
I've checked the board and tried the following suggestions:
Confirm content.rootDirectory it set - it is set to "Content"
Confirm content.load<> is accessing the resource via the correct path. Using reflection, I got the current directory for the application, and then used the rootdirectory + the path it was trying to access. The file definitely exists, is accessible, and is in that location.
Ensure ContentManager content is not null - confirmed using debugging, and that would throw a different exception anyway.
Confirm WAV is in 8 or 16 bit PCM. Confirmed.
Possible header corruption? This error occurs on any and all sound effects I attempt to load, so it is not a header issue pertaining to one file.
Oddly enough, this error seems to have come out of nowhere. It was working without problem for the past week, today its freaking out - and I haven't made any changes that would affect the content load process.
Here's the code throwing the error:
public void LoadSoundEffect(ContentManager content, String assetPath)
{
if (content != null && String.IsNullOrEmpty(assetPath) == false)
{
// This next line throws the exception.
SoundEffect effectLoader = content.Load<SoundEffect>(assetPath);
soundLibrary.Add(assetPath, effectLoader);
}
}
Here's the stacktrace:
at Microsoft.Xna.Framework.Helpers.ThrowExceptionFromErrorCode(Int32 error)
at Microsoft.Xna.Framework.Audio.SoundEffect.AllocateFormatAndData(Byte[] format, Byte[] > data, Int32 offset, Int32 count)
at Microsoft.Xna.Framework.Audio.SoundEffect.Create(Byte[] format, Byte[] data, Int32
offset, Int32 count, Int32 loopStart, Int32 loopLength, TimeSpan duration)
at Microsoft.Xna.Framework.Audio.SoundEffect..ctor(Byte[] format, Byte[] data, Int32
loopStart, Int32 loopLength, TimeSpan duration)
at Microsoft.Xna.Framework.Content.SoundEffectReader.Read(ContentReader input,
SoundEffect existingInstance)
at Microsoft.Xna.Framework.Content.ContentReader.InvokeReader[T](ContentTypeReader
reader, Object existingInstance)
at Microsoft.Xna.Framework.Content.ContentReader.ReadObjectInternal[T](Object
existingInstance)
at Microsoft.Xna.Framework.Content.ContentReader.ReadObjectT
at Microsoft.Xna.Framework.Content.ContentReader.ReadAssetT
at Microsoft.Xna.Framework.Content.ContentManager.ReadAsset[T](String assetName,
Action`1 recordDisposableObject)
at Microsoft.Xna.Framework.Content.ContentManager.Load[T](String assetName)
at SerializableDataTypes.AudioManager.LoadSoundEffect(ContentManager content, String
assetPath) in C:\Users\Mike\Documents\Visual Studio 2010\Projects\Res Judicata
Chapter1\SerializableDataTypes\Script Elements\AudioManager.cs:line 78
Thanks in advance for any help you can offer - I'm completely stumped on this, and it's a really frustrating error.
Just for curiosities sake, can you attempt loading your sound effect slightly differently.
SoundEffect effect = content.Load<SoundEffect>(String.Format(#"{0}", soundEffectPath))
I have had issues in the past loading certain content types when not using a string literal.

Categories