Question

Attributes are awesome. But is it possible to create a C# attribute class that, when tagged, makes your application minimize to the system tray?

Technically, the attribute would need to be placed on the class of the main form. Once the user clicks on the X button, that form shouldn't terminate, but should minimize to the taskbar. The icon for minimizing should also be specified in the attribute.

Is this technically feasible? I can't find any information on overwriting class code from an attribute placed on that class. (You need to at least overwrite one method to make it minimize to tray.)

Was it helpful?

Solution

Why not just do this:

class TrayForm : Form
{
    NotifyIcon notifyIcon = new NotifyIcon();
    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        if (e.CloseReason != CloseReason.WindowsShutDown && e.CloseReason != CloseReason.ApplicationExitCall)
        {
            e.Cancel = true;
            this.Hide();
            this.notifyIcon.Visible = true;
        }

        base.OnFormClosing(e);
    }

    protected override void OnSizeChanged(EventArgs e)
    {
        if (WindowState == FormWindowState.Minimized)
        {
            this.Hide();
            this.notifyIcon.Visible = true;
        }

        base.OnSizeChanged(e);
    }
}

OTHER TIPS

This could be achieved easier with form inheritance rather than attributes, something is still going to have to interpret the attributes at runtime to achieve the desired effect.

With inheritance you can just setup the class to behave the way you like and have essentially an opt-in or opt-out ability (even using an attribute to do so).

It's certainly possible but I'd suggest overriding the form close() method and simply put some minimizing code in there. It's simple, logical, and easy for future developers to follow.

Some sample code on how to achieve this is at:

http://www.dreamincode.net/code/snippet2660.htm

and

http://www.dreamincode.net/forums/showtopic116283.htm

It's not possible with the usual Form class. But it's possible to create an own class that inherits from Form and also supports such an attribute. But that would only make things unnecessary complicated, it would probably be better to add a MinimizeToTray property to that class.

(like the example PhilipW provided but with a property added to control the behavior)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top