On a Windows XP machine, the following code is throwing a System.ComponentModel.Win32Exception with the message "The operation completed successfully"
System.Drawing.Icon icon = new System.Drawing.Icon("icon.ico");
I can stop the program crashing with
try
{
System.Drawing.Icon icon = new System.Drawing.Icon("icon.ico");
}
catch(System.ComponentModel.Win32Exception ex)
{
if (ex.NativeErrorCode != 0)
{
throw;
}
}
but of course the icon is not set.
The full stack trace is
at System.Drawing.Icon.Initialize(Int32 width, Int32 height)
at System.Drawing.Icon..ctor(String fileName, Int32 width, Int32 height)
at System.Drawing.Icon..ctor(String fileName)
at hermes.Window1..ctor() in D:\\projects\\hermesclient\\hermesWPF\\hermes\\Window1.xaml.cs:line 50"
That line 50 is the original line I posted.
This is a WPF app, and on a Windows 7 machine the code works fine.
EDIT: Turned out the icon wasn't working in Windows XP at all, adding 256 colour versions seems to have fixed it.
From the looks of it the problem seems to be an issue with not disposing with objects properly. It's hard to pin point exactly where the issue in your case is occurring but as a general rule of thumb make sure you implement the using directive when dealing with objects that implement IDisposable.
Even in the sample you have provided try doing something like:
using (var icon = new System.Drawing.Icon("icon.ico"))
{
// use icon
}
// icon is then disposed.
Have a read of this article.
Does the file icon1.ico exists in the same directory as the .NET executable? You did not say explicitly...are you reading this as an external icon file? perhaps this
string sPath2Icon = Path.Combine(Environment.CurrentDirectory, "icon1.ico");
using (System.Drawing.Icon icon = new System.Drawing.Icon(sPath2Icon)){
// Do what you have to do with icon!
}
Hope this helps,
Best regards,
Tom.
I had a similar problem. in my case the icon file was a multiicon file containing 32x32, 48x48 and 256x256 size icons. I changed it to a single icon file size 32x32 and it worked fine after that.
Turned out the icon wasn't working in Windows XP at all, adding 256 colour versions seems to have fixed it.
Related
I writing Windows Forms Application application which should show image on the PictureBox control.
To retrieve this image from DICOMDIR file I use fo-dicom library (driven by this guide):
....
private void MainForm_Load(object sender, EventArgs e)
{
ImageManager.SetImplementation(WinFormsImageManager.Instance);
}
....
// this function is just for example
// real function is bit complicated
private void ShowImage()
{
// Getting DICOM file, retrieving all info from it
// Getting dicomDataset instance
....
var id = dicomDataset.Get<string>(DicomTag.ReferencedFileID, -1);
var dicomImage = new DicomImage(id);
var bitmap = dicomImage.RenderImage().AsBitmap();
pictureBox.Image = bitmap ?? pictureBox.ErrorImage;
}
When image is retrieving all works fine. But as soon as I maximize my MainForm, I got System.ArgumentException with Parameter is not valid message:
It looks like this is a .NET Framework bug, but maybe there is a way to fix it by overrideing OnPaint() method of PictureBox control?
Have anyone see this bug previously?
Thanks in advance.
P.S. During development this project I use following software:
Windows 10 x64
Visual Studio 2017 Community Edition
.NET Framework 4.5.1
fo-dicom version 3.0.2
EDIT #1
The same issue with Panel instead of PictureBox:
You are facing a known and already fixed bug in fo-dicom 3.0.2. See also https://github.com/fo-dicom/fo-dicom/issues/634.
For performance reason the Bitmap, that DicomImage.RenderImage().AsBitmap() returns, does not have its own pixel data, but has a pointer to the bytes of DicomImage. So the AsBitmap() does not duplicate all the pixel data in memory.
But if you instanciate the DicomImage in a local variable and save the Bitmap in the control, then the DicomImage is disposed at the end of the method and the pixel data gets garbace collected. The next time, the Bitmap tries to access the pixel data this exception happens.
The next release will have two methods: AsSharedBitmap() - the same as now but more obvious to the user - and AsClonedBitmap().
The workaround now is, to copy the pixel data manually by calling:
var bitmap = dicomImage.RenderImage().AsBitmap().Clone();
i'm part of a (small) development team who took over the development and support of a C#.Net program. It has ~ 300.000 LOC and the software design makes it impossible to change anything big without causing millions of side effects. It's like trying to turn a jungle full of poisenous snakes into a nice little garden. Using only a small scissor.
The application is a big WinForms-Application with Database access.
About the problem: A customer received our software and cannot run it. Unlike other customers, they have multiple Windows Server 2008 R1 terminal servers and installed the software on a network drive. Their users connect to one of the terminal servers and run our application (and others, like windows office etc) from the network drive. Our application however crashes after ~ 5 seconds without any notice. Our loading screen appears and closes again. The application produces a log file which shows this exception:
2014-08-04 11:15:23 [3372] ERROR – An exception occurred:
'OutOfMemoryException': Not enough memory.
System.Drawing
at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawImage(Image image, Rectangle destRect, Int32 srcX, Int32 srcY, Int32 srcWidth, Int32 srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttrs, DrawImageAbort callback, IntPtr callbackData)
at System.Drawing.Bitmap.MakeTransparent(Color transparentColor)
at System.Windows.Forms.ImageList.CreateBitmap(Original original, Boolean& ownsBitmap)
at System.Windows.Forms.ImageList.CreateHandle()
at System.Windows.Forms.ImageList.get_Handle()
at System.Windows.Forms.ImageList.GetBitmap(Int32 index)
at System.Windows.Forms.ImageList.ImageCollection.GetEnumerator()
at <our application>.InitializeHtmlResources()
The method that calls ImageCollection.GetEnumerator() is this:
void InitializeHtmlResources()
{
string baseDirPath = ... //It's in AppData/Local/<ourFolder>/Icons;
int index = -1;
foreach (Image image in UIResources.Icons.Images)
{
index += 1;
image.Save(baseDirPath + Path.DirectorySeparatorChar + index.ToString(), ImageFormat.Png);
}
}
Those images are stored inside a Resource.Icons.dll. The icons have their own project in the solution that contains of a few helper classes (like UIResources) and contains a folder with every icon we use + an xml where they are all listed, named and indexed. UIResources is a static class that allows access to the icons and the image list. This is how the property "Images" is initialized:
...
// Code snippet of Images Initialization
var ilist = new ImageList();
ilist.ColorDepth = ColorDepth.Depth32Bit;
ilist.ImageSize = new Size(16, 16);
ilist.TransparentColor = Color.Fuchsia;
UIResources.Icons.Images = ilist;
...
This method is used to extract an Icon from the DLL file.
static IEnumerable<IconInfo> GetIcons()
{
XDocument doc;
using (var stream = GetResourceStream("Our.Namespace.Resources.Icons.Icons.xml"))
{
doc = XDocument.Load(stream);
}
// ReSharper disable once PossibleNullReferenceException
foreach (var elem in doc.Element("Icons").Elements("Icon"))
{
int index = (int)elem.Attribute("Index");
var bmp = ReadIcon("Icons", (string)elem.Attribute("FileName"));
string name = (string)elem.Attribute("Name");
yield return new IconInfo(bmp, index, name);
}
}
static Bitmap ReadIcon(string kind, string fileName)
{
using (var stream = GetResourceStream("Our.Namespace.Resources." + kind + "." + fileName))
{
return new Bitmap(stream);
}
}
static Stream GetResourceStream(string resourceName)
{
return typeof(IconProvider).Assembly.GetManifestResourceStream(resourceName);
}
IconInfo is only a record containing the values.
And finally, the ImageList is filled with values:
foreach (var icon in GetIcons())
UIResources.Icons.Images.Add(icon.Name, icon.Image);
The application works fine. But when that customer runs the software on his terminal server via Remote Desktop, the application crashes and throws an OutOfMemory Exception in InitializeHtmlResources() right at the foreach-loop (when accessing the enumerator of ImageList).
The confusing part: A "OutOfMemory" exception is thrown, though the memory is neither full, nor is the 2 GB limit for 32bit application reached. The app peaks at 120 MB during loading.
I have absolutely no idea how this error is caused and spent the last 2-3 days trying to find a solution. I haven't.
I appreciate every bit of advice you can give me.
EDIT:
I tried disabling the InitializeHtmlResources-Method. This enabled the application to start. However: After working a few seconds with the application, an outofmemory exception appeared anyway. The cause is another ImageList accessor.
It works fine with Server 2012. We created a VM with Windows Server 2008 and the error happens there too.
We found the issue! Instead of
UIResources.Icons.Images.Add(icon.Name, icon.Image);
to fill the ImageList, we now use
UIResources.Icons.Images.Add(icon.Name, new Bitmap(icon.Image));
Now our application works on Windows Server 2008 :-)
Is it possible?
Memory limitations of 32 bit apps on 64 bit Terminal Server 2008 Standard
I'm making a windows form application using Visual Studio. The application allows you to enter the what you want the photo to be named, and then saves that image to a specific location on the network. It works great when I use it on my laptop. However, when I try to run it on the a desktop, it does not work. Instead I get the message:
System.Runtime.InteropServices.COMException (0x80040217): No
combination of intermediate filters could be found to make the
connection.
at DirectShowLib.DsError.ThrowExceptionForHR(Int32 hr)
at OrderProductCapture.Capture.SetupGraph(DsDevice dev, Int32 iWidth,
Int32 iHeight, Int16 iBPP, Control hControl)
at OrderProductCapture.Capture.ctor(Int32 iDeviceNum, Int32 iWidth,
Int32 iHeight, Int16 iBPP, Control hControl)
at OrderProductCapture.frmMain.ctor()
The Call Stack says:
OrderProductCapture.exe!OrderProductCapture.Capture(int iDeviceNum, int iWidth, int iHeight, short iBPP, System.Windows.Forms.Control hControl) Line 82
OrderProductCapture.exe!OrderProductCapture.frmMain.frmMain() Line 50
OrderProductCapture.exe!OrderProductCapture.Program.Main() Line 19
I have already googled this many times, and I've looked at most of the similar questions on SO. Both computers are using Windows 7 professional. Any help would be fantastic.
This is the code where my code catches the exception. I do not think the code is wrong, because it works fine on my laptop.
public Capture(int iDeviceNum, int iWidth, int iHeight, short iBPP, Control hControl)
{
DsDevice [] capDevices;
// Get the collection of video devices
capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
if (iDeviceNum + 1 > capDevices.Length)
{
throw new Exception("No video capture devices found at that index!");
}
try
{
// Set up the capture graph
SetupGraph( capDevices[iDeviceNum], iWidth, iHeight, iBPP, hControl);
// tell the callback to ignore new images
m_PictureReady = new ManualResetEvent(false);
}
catch
{
Dispose();
throw;
}
}
When having to convert between media formats, you can programmatically force it to use some specific filter chain and configure it tightly to your needs, but DirectSHOW also has the ability of "guessing" the right tools to use. It knows all the tiny media handlers that are oficially installed in the OS, and tries to match them so that final required "conversion" is built.
However, DirectShow still needs those tiny converters to be installed. DS is able to analyze and connect them, but will not provide you any support for exotic media types. Often, even non-exotic can be problematic if the OS is "fresh-n-clean".
If I remember correctly, that error basically means that (on this problematic machine) some "codecs" are missing.
These things often come with any:
drivers for webcams/microphones/soundcards
audio-processing software (sound editors, media recorders, media players, ..)
"codec packs" like CCCP (really, don't get confused by their logo)
specific codec/filter packages
(...)
First thing I'd now do would be:
recall what I tried to convert
try to read all error messages and logs and find out if there's some faulty filter mentioned, maybe it needs reinstalling
compare what audio-related software is installed on machines where the program WORKS versus the problematic machine
basing on the above, try to deduce what codec is missing
find it, download, install
Also, you may read the code of SetupGraph() function. I bet there's a clear reference to the format that is being used, and this may point out what codec is missing.
Codecs also sometimes get damaged (actually not themselves, but their configuration and registration entries may get damaged). If you are sure that the correct codecs are available on the machine, reinstalling or "repairing" (if they have such option) them can help.
I've been fine with Screen.PrimaryScreen.Bounds.Size for some time, but on my Windows7 computer attached to my big-screen TV it is giving me incorrect values.
I read elsewhere to try SystemInformation.PrimaryMonitorSize but that gives the same values.
When I right click the desktop to get Screen Resolution, it says 1920x1080. The above two are giving me 1280x720.
I've also tried the WPF versions:
var w = System.Windows.SystemParameters.PrimaryScreenWidth;
var h = System.Windows.SystemParameters.PrimaryScreenHeight;
MessageBox.Show(new Size((int)w, (int)h).ToString());
The display size has been changed via the (right click the desktop) Personalize > Desktop options to be 150% (since the screen is 60" and you sit kind of far away).
How to detect this so the value's returned from the above can be adjusted?
Note: I've discovered how to get around this with a right-click executable and adjust the compatability to disable DPI virtualization, but I still need a programatic solution so I don't have to have user's adjust this themselves: See - http://msdn.microsoft.com/en-us/library/dd464660(VS.85).aspx#dpi_virtualization
It could be your Dpi setting in windows set above 100%
Try using this method, this will scale the resolution to the current system Dpi settings
Winforms:
private Size GetDpiSafeResolution()
{
using (Graphics graphics = this.CreateGraphics())
{
return new Size((Screen.PrimaryScreen.Bounds.Width * (int)graphics.DpiX) / 96
, (Screen.PrimaryScreen.Bounds.Height * (int)graphics.DpiY) / 96);
}
}
WPF:
private Size GetDpiSafeResolution()
{
PresentationSource _presentationSource = PresentationSource.FromVisual(Application.Current.MainWindow);
Matrix matix = _presentationSource.CompositionTarget.TransformToDevice;
return new System.Windows.Size(
System.Windows.SystemParameters.PrimaryScreenWidth * matix.M22,
System.Windows.SystemParameters.PrimaryScreenHeight * matix.M11);
}
Note: Make sure your MainWindow is loaded before running this code
I don't feel this is a duplicate question, but the answer is the same as on another thread: https://stackoverflow.com/a/13228495/353147 As the question isn't about blurry fonts but why Screen.PrimaryScreen.Bounds.Size returns faulty information. It could help others.
I did run into an error message, that mscorlib threw an null error. From this thread http://forums.asp.net/t/1653876.aspx/1 I was able to discover that unchecking "Enable ClickOnce security settings" fixed it. This seems like a hack, but it works.
I'm making a small app in C# (.net 4.0, VS 2012), and as part of it I need to extract an icon of another EXE file.
I found that I can use ExtractVistaIcon in a combination with TKageyu.Utils.
The problem is, there is no such thing TKageyu.Utils as what VS.net 2012 says.
using TKageyu.Utils;
Results with:
"The type or namespace name 'TKageyu' could not be found"
What should I do? Where can I get it?
The code I'm trying to use it with:
using (TKageyu.Utils.IconExtractor IconEx = new TKageyu.Utils.IconExtractor(fullPath))
{
Icon icoAppIcon = IconEx.GetIcon(0); // Because standard System.Drawing.Icon.ExtractAssociatedIcon() returns ONLY 32x32.
picboxAppLogo.Image = ExtractVistaIcon(icoAppIcon);
}
Original code taken from:
Using 256 x 256 Vista icon in application
(Will be edited by me when I get it to work)
Thanks to #Simon McKenzie I found this way to solve my problem:
Go to http://www.codeproject.com/Articles/26824/Extract-icons-from-EXE-or-DLL-files
Download the app
Open the SLN file in Visual Studio (I did in 2012)
Open Form1.cs, copy the namespace there and the includes (just to make sure..)
Go to your project and paste the namespace in the file you need it,
Also check that you have all the includes that the namespace needed in the other file.
USE IT! :)
I used it like so:
using (TKageyu.Utils.IconExtractor IconEx = new TKageyu.Utils.IconExtractor(fullPath))
{
Icon icoAppIcon = IconEx.GetIcon(0); // Because standard System.Drawing.Icon.ExtractAssociatedIcon() returns ONLY 32x32.
Bitmap hBitmap = ExtractVistaIcon(icoAppIcon);
IntPtr hLBitmap = hBitmap.GetHbitmap();
ImageSource wBitmap = Imaging.CreateBitmapSourceFromHBitmap(hLBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
IconBox_1.Source = wBitmap;
IconBox_S.Source = wBitmap;
IconBox_C.Source = wBitmap;
IconBox_W.Source = wBitmap;
}