Jump to content
  • Advertisement
Sign in to follow this  
DaWanderer

[.net] Useful pieces of code

This topic is 4486 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have some pieces of code that I've found very useful over the years and I'd though I'd share them. Post your own useful snippets! This one is the timer class I've used for my games for quite a while (ported from C++ a few years ago). After calling the Start method, the GetTimeElasped method will report the number of seconds since Start was called.
using System;
using System.Runtime.InteropServices;

namespace Utility
{
    public class GameTimer
    {
        private long frequency = 0, startTime = 0;

        //Imported functions
        [DllImport("kernel32.dll")]
        private extern static short QueryPerformanceCounter(ref long x);
        [DllImport("kernel32.dll")]
        private extern static short QueryPerformanceFrequency(ref long x);

        public GameTimer()
        {
            //Get timer frequency
            QueryPerformanceFrequency(ref frequency);
        }

        public void Start()
        {
            //Get the current time
            QueryPerformanceCounter(ref startTime);
        }

        public double GetElapsedTime()
        {
            long endTime = startTime;
            double returnTime = 0;

            //Get the current time
            QueryPerformanceCounter(ref endTime);

            //Calculate elapsed time
            returnTime = (double)(endTime - startTime) / frequency;

            return (returnTime);
        }
    }
}

The GetIconFromExtension method will get the Windows default icon for a given file name by examining the extension. If no icon is found, it returns a default Windows icon (which seems to be the same one used for DLL's).
using System;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;

using Microsoft.Win32;

namespace Utility
{
	public class Win32
	{
		[DllImport("Shell32", CharSet=CharSet.Auto)]
		internal extern static int ExtractIconEx (
			[MarshalAs(UnmanagedType.LPTStr)] 
			string lpszFile,       //size of the icon
			int nIconIndex,        //index of the icon (in case we have
			//more then 1 icon in the file
			IntPtr[] phIconLarge,  //32x32 icon
			IntPtr[] phIconSmall,  //16x16 icon
			int nIcons);           //how many to get

		public static Icon GetIconFromExtension(string fileName, IconSize size)
		{
			Icon returnIcon;

			try
			{
				FileInfo fileInfo = new FileInfo(fileName);
				RegistryKey classKey = Registry.ClassesRoot.OpenSubKey(fileInfo.Extension);
				string classKeyName = classKey.GetValue("").ToString();
				RegistryKey classNameKey = Registry.ClassesRoot.OpenSubKey(classKeyName);
				string iconInfo = classNameKey.OpenSubKey("DefaultIcon").GetValue("").ToString();
				string[] iconNameNumber = iconInfo.Split(',');

				string iconFileName = iconNameNumber[0];
				Int16 iconNumber = 0;

				if (iconNameNumber.Length > 1)
				{
					if (iconNameNumber[1] != null)
					{
						iconNumber = Int16.Parse(iconNameNumber[1]);
					}
				}

				IntPtr[] largeIcon = new IntPtr[1], smallIcon = new IntPtr[1];
				ExtractIconEx(iconFileName, (int)iconNumber, largeIcon, smallIcon, 1);

				returnIcon = (size == IconSize.Large) ? Icon.FromHandle(largeIcon[0]) : Icon.FromHandle(smallIcon[0]);
			}
			catch
			{
				IntPtr[] largeIcon = new IntPtr[1], smallIcon = new IntPtr[1];
				ExtractIconEx(@"C:\Windows\system32\shell32.dll", (int)-154, largeIcon, smallIcon, 1);
				returnIcon = (size == IconSize.Large) ? Icon.FromHandle(largeIcon[0]) : Icon.FromHandle(smallIcon[0]);
			}
			
			return(returnIcon);
		}
	}

	public enum IconSize
	{
		Large, Small
	}
}

I hope someone finds these pieces of code useful!

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by Ridge
For folks running 2.0 I'd recommend System.Diagnostics.Stopwatch.


I never knew it existed. One more thing to make my code more cross platform for the future. Thanks!

Share this post


Link to post
Share on other sites
Yeah, it seems it's often overlooked. It wraps QPC, if available, otherwise it falls back on DateTime's ticks. Unfortunately, at last check Mono doesn't yet have an implementation for it, but I suspect they'll have it added fairly soon.

Share this post


Link to post
Share on other sites
Quote:
Original post by Roboguy
Does it have to be in a .NET language?


Well, since it is a .NET forum....however, my examples both use P/Invoke, which could be considered "un-.NET".

Share this post


Link to post
Share on other sites
A very nice high resolution timer was brought up by nagromo in this thread: Timing Is Everything. It uses the High Performance Timer by default, and Environment.TickCount if the high performance timer isn't available (if you're running on Mono/Linux).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!