How to get the running exe File Version

C#, C# Language, Win Forms 1 Comment »

 

Nice and simple, get the running assembly, get the AssemblyName details object, get the version property.

 

            Assembly asm =  Assembly.GetExecutingAssembly();
            AssemblyName AssDetails = asm.GetName();
            String versionAsString = AssDetails.Version.ToString();

Receive Key Messages irrespective of Key Modifiers

C#, Component Development, Win Forms No Comments »

As covered in a previous article, you can overrride the IsInputKey method on a control to inform winforms that you require keyboard event notification for special keys like tabe and cursor keys which are used but the hosting form for control navigation.

When writing a control, I was trying to capture the SHIFT - Right Cursor combination.  I already had the following implementation in IsInputKey

                        switch (keyData)

            {
                case Keys.Up:
                case Keys.Down:
                case Keys.Left:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                    {
                        return true;
                    }
            }
            return base.IsInputKey(keyData);
 

However, althought control-Right and Alt-Right events came through Shift-Right wouldn’t.  These were passed to the base implementation which returned true to be handled by the control but fals for the shift right.

So to force the processing of keys irrespective of the key modifiers simply chnage the case statement to read

            switch (keyData & ~Keys.Modifiers)

 Which removes and modifier bit flags from the keydata fro the switch comparison.

How to determine if a control or one of it’s child controls has focus

C#, Component Development, Win Forms 1 Comment »

Focus returns a boolean to indicate whether or not a control has focus or not, but when trying to paint your own focus rectangle in your control and you have allowed your controls scrollbars to accept focus, then the Focus property will return false. 

Instead of using Focus, check the ContainsFocus property that returns true if the control or a child control has focus.

Notifying the Collection Editor of changes

C#, Component Development, Win Forms No Comments »

When you are building your own collections of objects it is common to use an overridden ToString implementation to display some property of your object in the collection editor instead of the full class name which is the default.

For example, when developing a Column collection, I override the ToString() to return the Columns caption.  However, when the caption property of my column is updated in the standard collection editor, the respective item in the list of items in the collection editor is not updated. 

The collection editor can be notified to refresh it’s properties and therefore the list by adding a RefreshProperties attribute to the property that causes the required change.

e.g.

    public class TreeColumn
    {
        private String _Caption;
 
        [RefreshProperties(RefreshProperties.All)]
        [Browsable(true)]
        [Description("The Caption for the column")]
        public String Caption
        {
            get { return _Caption; }
            set { _Caption = value; }
        }
 
        public override string ToString()
        {
            if (!String.IsNullOrEmpty(_Caption))
                return _Caption;
            return base.ToString();
        }
    }

Runtime Resizable Panel Control

C#, Component Development, Win Forms 1 Comment »

Below is a complete resizable panel the can be resized on the right and bottom. It uses the windows SysCommand message and some little know options to cause the window (control) to resize.

If you want to allow moving or resizing in other directions, then extend the mouse location check and call the appropriate syscommand values.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Runtime.InteropServices;

 

namespace YourAssembly

{

    public partial class ResizablePanel : Panel

    {

        private Boolean _ResizeParent;

 

        private class NativeCalls

        {

            [DllImport("USER32.DLL", EntryPoint = "SendMessage")]

            public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, ref int lParam);

            [DllImport("user32")]

            public static extern int ReleaseCapture(IntPtr hwnd);

            public const int WM_SYSCOMMAND = 0×0112;

            public const int SC_DRAGMOVE = 0xF012;

            public const int SC_DRAGSIZE_N = 0xF003;

            public const int SC_DRAGSIZE_S = 0xF006;

            public const int SC_DRAGSIZE_E = 0xF002;

            public const int SC_DRAGSIZE_W = 0xF001;

            public const int SC_DRAGSIZE_NW = 0xF004;

            public const int SC_DRAGSIZE_NE = 0xF005;

            public const int SC_DRAGSIZE_SW = 0xF007;

            public const int SC_DRAGSIZE_SE = 0xF008;

        }

 

        public Boolean ResizeParent

        {

            get { return _ResizeParent; }

            set { _ResizeParent = value; }

        }

 

        public ResizablePanel()

        {

            InitializeComponent();

            MinimumSize = new Size(50, 50);

            Margin = new Padding(0, 0, 0, 0);

            Padding = new Padding(0, 0, 3, 3);

            BackColor = SystemColors.ControlLight;

        }

 

        private enum MousePos {NoWhere, Right, Bottom, BottomRight}

       

        private MousePos GetMousePos(Point location)

        {

            MousePos result = MousePos.NoWhere;

 

            Rectangle TestRect;

 

            int RightSize = Padding.Right;

            int BottomSize = Padding.Bottom;

 

            // Resize right border

            TestRect = new Rectangle(Width - RightSize, 0, Width - RightSize, Height - BottomSize);

            if (TestRect.Contains(location)) result = MousePos.Right;

 

            // Resize bottom border

            TestRect = new Rectangle(0, Height - BottomSize, Width - RightSize, Height);

            if (TestRect.Contains(location)) result = MousePos.Bottom;

 

            // Resize bottom Corner

            TestRect = new Rectangle(Width - RightSize, Height -BottomSize, Width, Height);

            if (TestRect.Contains(location)) result = MousePos.BottomRight;

            return result;

        }

 

        protected override void OnMouseDown(MouseEventArgs e)

        {

            base.OnMouseDown(e);

 

            IntPtr hwnd = this.Handle;

 

            if ((ResizeParent) && (this.Parent != null) && (this.Parent.IsHandleCreated))

            {

                hwnd = Parent.Handle;

            }

 

            int nul = 0;

            MousePos mousePos = GetMousePos(e.Location);

            switch (mousePos)

            {

                case MousePos.Right:

                    {

                        NativeCalls.ReleaseCapture(hwnd);

                        NativeCalls.SendMessage(hwnd, NativeCalls.WM_SYSCOMMAND, NativeCalls.SC_DRAGSIZE_E, ref nul);

                    } break;

                case MousePos.Bottom:

                    {

                        NativeCalls.ReleaseCapture(hwnd);

                        NativeCalls.SendMessage(hwnd, NativeCalls.WM_SYSCOMMAND, NativeCalls.SC_DRAGSIZE_S, ref nul);

                    } break;

                case MousePos.BottomRight:

                    {

                        NativeCalls.ReleaseCapture(hwnd);

                        NativeCalls.SendMessage(hwnd, NativeCalls.WM_SYSCOMMAND, NativeCalls.SC_DRAGSIZE_SE, ref nul);

                    } break;

            }

 

        }

 

        protected override void OnMouseMove(MouseEventArgs e)

        {

            base.OnMouseMove(e);

 

            MousePos mousePos = GetMousePos(e.Location);

            switch (mousePos)

            {

                case MousePos.Right: Cursor = Cursors.SizeWE; break;

                case MousePos.Bottom: Cursor = Cursors.SizeNS; break;

                case MousePos.BottomRight: Cursor = Cursors.SizeNWSE; break;

                default: Cursor = Cursors.Default; break;

            }

        }

 

        protected override void OnResize(EventArgs eventargs)

        {

            base.OnResize(eventargs);

            if (this.Width < this.MinimumSize.Width) this.Width = this.MinimumSize.Width;

            if (this.Height < this.MinimumSize.Height) this.Height = this.MinimumSize.Height;

        }

 

        protected override void OnMouseLeave(EventArgs e)

        {

            base.OnMouseLeave(e);

            Cursor = Cursors.Default;

        }

    }

 

 

}

 

Custom Exceptions and Serialization.

C#, C# Language, Win Forms No Comments »

Microsoft state that if you want to raise custom exceptions in your application then you should derive them from the ApplicationException class and not the Exception class.

ApplicationException is thrown by a user program, not by the common language runtime. If you are designing an application that needs to create its own exceptions, derive from the ApplicationException class. ApplicationException extends Exception, but does not add new functionality. This exception is provided as means to differentiate between exceptions defined by applications versus exceptions defined by the system.

However, the blog entry by Microsoft’s Brad Adams states that ApplicationException should not be used !

I found that descending from Exception, at least gives a nice error message detailing the exception that was raised as opposed to ApplicationExceptiosn, “Application Error ocurred” message.

So how do we serialize a custom exception class ?

Step 1) Add the Serializable attribute to the exception

Step 2) Provide a contructor that takes the serialization information and context e.g. MyException(SerializationInfo info, StreamingContext context)
Step 3) If you have a constructor that passes state information to the exception to be included in the data collection ensure this is copied from the exception object to the info in the serialization constructor (step2)

e.g.

[csharp]

[Serializable]
public class MyException : Exception
{
public MyException(String sessionId)
: base()
{
this.Data.Add(”SessionID”, sessionId);
}

public MyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
info.AddValue(”SessionID”,Data["SessionID"]);
}

public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
}
[/csharp]

How to access resources, eg use a resource image

C#, Graphics and Images, Win Forms No Comments »

In Visual Studio 2005, (im not sure about other versions), simply choose properties on the Assembly and add the Resources you need under the resource tab.
In the class file you want to access the resources in, add a using statement
[csharp]using MyProject.Properties;[/csharp]
You can now access the resources in code by using the static Resource class.

[csharp]MyGraphics.DrawImage(Resources.MyImageResourceName, new Point(0,0));[/csharp]

How to get Mouse Position and Cursor information

C#, Component Development, Win Forms No Comments »

If you want to set or retrieve the current mouse position, or turn the cursor on or off, use the static Cursor class.

Point CursorPos = Cursor.Position

WP Theme &Design by minus19.com & Icons
Entries RSS Comments RSS Log in