Initial import of mono-snippets

svn path=/trunk/mono-snippets/; revision=54638
This commit is contained in:
Aaron Bockover 2005-12-20 00:31:31 +00:00
Коммит 96334f6e5c
15 изменённых файлов: 844 добавлений и 0 удалений

8
AUTHORS Normal file
Просмотреть файл

@ -0,0 +1,8 @@
Mono Snippets Maintainer:
Aaron Bockover <aaron@aaronbock.net>
NotificationAreaIcon:
Todd Berman <tberman@off.net>
Ed Catmur <ed@catmur.co.uk>
Aaron Bockover <aaron@aaronbock.net>

5
COPYING Normal file
Просмотреть файл

@ -0,0 +1,5 @@
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

7
ChangeLog Normal file
Просмотреть файл

@ -0,0 +1,7 @@
2005-12-19 Aaron Bockover <aaron@aaronbock.net>
* src/NotificationAreaIcon/*: Added the NotificationAreaIcon class and
wrote a sample program for it
* mono-snippets: Set up initial project and build system

46
HACKING Normal file
Просмотреть файл

@ -0,0 +1,46 @@
It is important that *both* the MonoDevelop solution file and project files
remain in sync with the autotools build scripts.
If you add a new snippet, add it under src/, and use the NotificationAreaIcon
snippet as an example for creating the Mono Develop project file and the
autotools Makefile.am file.
Basically, here's how to create a new snippet named "NewSnippet":
---------------
[edit configure.ac to output src/NewSnippet/Makefile]
[
edit mono-snippets.mds and add the following entry to the <Entries> element,
replacing NewSnippet with the name of your snippet:
<Entry filename="./src/NewSnippet/snippet.mdp" />
]
cd src/
cp -rf NotificationAreaIcon NewSnippet
[edit Makefile.am; add "NewSnippet" to SUBDIRS]
cd NewSnippet
[
edit Makefile.am; change the SNIPPET_NAME and SOURCE variables to
the name of your snippet (same name as the directory, "NewSnippet")
and add names of the .cs source files
]
[
edit snippet.mdp to reflect name change from NotificationAreaIcon to
NewSnippet. A simple search/replace should be all that is needed.
]
---------------
Snippets should be relatively short. Just one main class and a sample of
using the class. The class .cs file should have the same name as the sample
directory (i.e. the main class for the NewSnippet snippet is NewSnippet.cs),
and the sample code should be in a file Sample.cs. This keeps the snippets
simple!

24
Makefile.am Normal file
Просмотреть файл

@ -0,0 +1,24 @@
SUBDIRS = src
EXTRA_DIST = mono-snippets.mds HACKING
DISTCLEANFILES = \
*.bak \
*~ \
*.pidb
MAINTAINERCLEANFILES = \
compile \
INSTALL \
config.h.in \
aclocal.m4 \
ltmain.sh \
Makefile.in \
depcomp \
missing \
install-sh \
configure \
config.sub \
config.guess \
mkinstalldirs

0
NEWS Normal file
Просмотреть файл

7
README Normal file
Просмотреть файл

@ -0,0 +1,7 @@
Mono Snippets is a simple project that contains commonly shared code in
Mono/Gtk# applications, like the NotificationAreaIcon class. It is the
central maintainence point for such "snippets" of code, and contains
example programs for each snippet.
Think of Mono Snippets as "egg" for Mono

85
autogen.sh Executable file
Просмотреть файл

@ -0,0 +1,85 @@
#! /bin/sh
# Ok, simple script to do this.
: ${AUTOCONF=autoconf}
: ${AUTOHEADER=autoheader}
: ${AUTOMAKE=automake}
: ${LIBTOOLIZE=libtoolize}
: ${ACLOCAL=aclocal}
: ${LIBTOOL=libtool}
srcdir=`dirname $0`
test -z "$srcdir" && srcdir=.
ORIGDIR=`pwd`
cd $srcdir
PROJECT=mono-snippets
TEST_TYPE=-f
FILE=README
CONFIGURE=configure.ac
aclocalinclude="-I . $ACLOCAL_FLAGS"
DIE=0
($AUTOCONF --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "You must have autoconf installed to compile $PROJECT."
echo "Download the appropriate package for your distribution,"
echo "or get the source tarball at ftp://ftp.gnu.org/pub/gnu/"
DIE=1
}
($AUTOMAKE --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "You must have automake installed to compile $PROJECT."
echo "Get ftp://sourceware.cygnus.com/pub/automake/automake-1.4.tar.gz"
echo "(or a newer version if it is available)"
DIE=1
}
(grep "^AM_PROG_LIBTOOL" configure.ac >/dev/null) && {
($LIBTOOL --version) < /dev/null > /dev/null 2>&1 || {
echo
echo "**Error**: You must have \`libtool' installed to compile $PROJECT."
echo "Get ftp://ftp.gnu.org/pub/gnu/libtool-1.2d.tar.gz"
echo "(or a newer version if it is available)"
DIE=1
}
}
if test "$DIE" -eq 1; then
exit 1
fi
test $TEST_TYPE $FILE || {
echo "You must run this script in the top-level $PROJECT directory"
exit 1
}
if test -z "$*"; then
echo "I am going to run ./configure with no arguments - if you wish "
echo "to pass any to it, please specify them on the $0 command line."
fi
case $CC in
*xlc | *xlc\ * | *lcc | *lcc\ *) am_opt=--include-deps;;
esac
(grep "^AM_PROG_LIBTOOL" configure.ac >/dev/null) && {
echo "Running $LIBTOOLIZE ..."
$LIBTOOLIZE --force --copy
}
echo "Running $ACLOCAL $aclocalinclude ..."
$ACLOCAL $aclocalinclude
echo "Running $AUTOMAKE --gnu $am_opt ..."
$AUTOMAKE --add-missing --gnu $am_opt
echo "Running $AUTOCONF ..."
$AUTOCONF
echo Running $srcdir/configure $conf_flags "$@" ...
$srcdir/configure --enable-maintainer-mode $conf_flags "$@" \

34
configure.ac Normal file
Просмотреть файл

@ -0,0 +1,34 @@
AC_INIT(README)
AC_CANONICAL_SYSTEM
AM_INIT_AUTOMAKE(mono-snippets, 0.1)
AM_MAINTAINER_MODE
AC_PATH_PROG(MONO, mono, no)
if test "x$MONO" = "xno"; then
AC_MSG_ERROR([Cannot find "mono" runtime in your PATH])
fi
AC_PATH_PROG(MCS, mcs, no)
if test "x$MCS" = "xno"; then
AC_MSG_ERROR([Cannot find "mcs" compiler in your PATH])
fi
PKG_CHECK_MODULES(GTKSHARP, gtk-sharp-2.0 >= 2.3.92)
AC_OUTPUT([
Makefile
src/Makefile
src/NotificationAreaIcon/Makefile
])
echo "
** Note: There is no need to run \`make install' **
You can test the snippet examples simply by
running \`make run' in the respective snippet
source directory.
\`make install' still works however.
"

16
mono-snippets.mds Normal file
Просмотреть файл

@ -0,0 +1,16 @@
<Combine name="Mono Snippets" fileversion="2.0">
<Configurations active="Release">
<Configuration name="Debug" ctype="CombineConfiguration">
<Entry configuration="Debug" build="True" name="NotificationAreaIcon" />
</Configuration>
<Configuration name="Release" ctype="CombineConfiguration">
<Entry configuration="Debug" build="True" name="NotificationAreaIcon" />
</Configuration>
</Configurations>
<StartMode startupentry="NotificationAreaIcon" single="True">
<Execute type="None" entry="NotificationAreaIcon" />
</StartMode>
<Entries>
<Entry filename="./src/NotificationAreaIcon/snippet.mdp" />
</Entries>
</Combine>

6
src/Makefile.am Normal file
Просмотреть файл

@ -0,0 +1,6 @@
SUBDIRS = \
NotificationAreaIcon
DISTCLEANFILES = \
Makefile.in

Просмотреть файл

@ -0,0 +1,28 @@
SNIPPET_NAME = NotificationAreaIcon
SOURCES = \
$(srcdir)/NotificationAreaIcon.cs \
$(srcdir)/Sample.cs
# The following should not need editing unless you need to do something
# advanced, add a resource, reference, etc, etc, etc, etc
# If you need to add references to assemblies other than gtk-sharp-2.0,
# be sure to keep them in sync with the MonoDevelop project file!!
ASSEMBLY = $(SNIPPET_NAME).exe
snippetsdir = $(pkglibdir)
snippets_SCRIPTS = $(ASSEMBLY)
all: $(ASSEMBLY)
run: all
$(MONO) $(ASSEMBLY)
$(ASSEMBLY): $(SOURCES)
$(MCS) -out:$(ASSEMBLY) $(GTKSHARP_LIBS) $(SOURCES)
EXTRA_DIST = $(SOURCES) snippet.mdp
CLEANFILES = $(ASSEMBLY) $(ASSEMBLY).mdb $(SNIPPET_NAME).pidb
DISTCLEANFILES = Makefile.in

Просмотреть файл

@ -0,0 +1,461 @@
/* -*- Mode: csharp; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: t -*- */
/***************************************************************************
* NotificationAreaIcon.cs
*
* Copyright (C) 2005 Todd Berman <tberman@off.net>
* Copyright (C) 2005 Ed Catmur <ed@catmur.co.uk>
* Copyright (C) 2005 Novell, Inc. (Miguel de Icaza, Aaron Bockover)
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
// NOTE: throughout IntPtr is used for the Xlib long type, as this tends to
// have the correct width and does not require any configure checks.
using System;
using System.Runtime.InteropServices;
using Gtk;
using Gdk;
#pragma warning disable 0169
public class NotificationAreaIcon : Plug
{
private uint stamp;
private Orientation orientation;
private int selection_atom;
private int manager_atom;
private int system_tray_opcode_atom;
private int orientation_atom;
private IntPtr manager_window;
private FilterFunc filter;
public NotificationAreaIcon (string name)
{
Title = name;
Init ();
}
public NotificationAreaIcon (string name, Gdk.Screen screen)
{
Title = name;
Screen = screen;
Init ();
}
public uint SendMessage (uint timeout, string message)
{
if (manager_window == IntPtr.Zero) {
return 0;
}
SendManagerMessage (SystemTrayMessage.BeginMessage, (IntPtr) Id, timeout, (uint) message.Length, ++stamp);
gdk_error_trap_push ();
for (int index = 0; index < message.Length; index += 20) {
XClientMessageEvent ev = new XClientMessageEvent ();
IntPtr display = gdk_x11_display_get_xdisplay (Display.Handle);
ev.type = XEventName.ClientMessage;
ev.window = (IntPtr) Id;
ev.format = 8;
ev.message_type = (IntPtr) XInternAtom (display, "_NET_SYSTEM_TRAY_MESSAGE_DATA", false);
byte [] arr = System.Text.Encoding.UTF8.GetBytes (message.Substring (index));
int len = Math.Min (arr.Length, 20);
Marshal.Copy (arr, 0, ev.data.ptr1, len);
XSendEvent (display, manager_window, false, EventMask.StructureNotifyMask, ref ev);
XSync (display, false);
}
gdk_error_trap_pop ();
return stamp;
}
public void CancelMessage (uint id)
{
if (id == 0) {
return;
}
SendManagerMessage (SystemTrayMessage.CancelMessage, (IntPtr) Id, id, 0, 0);
}
private void Init ()
{
stamp = 1;
orientation = Orientation.Horizontal;
AddEvents ((int)EventMask.PropertyChangeMask);
filter = new FilterFunc (ManagerFilter);
}
protected override void OnRealized ()
{
base.OnRealized ();
Display display = Screen.Display;
IntPtr xdisplay = gdk_x11_display_get_xdisplay (display.Handle);
selection_atom = XInternAtom (xdisplay, "_NET_SYSTEM_TRAY_S" + Screen.Number.ToString (), false);
manager_atom = XInternAtom (xdisplay, "MANAGER", false);
system_tray_opcode_atom = XInternAtom (xdisplay, "_NET_SYSTEM_TRAY_OPCODE", false);
orientation_atom = XInternAtom (xdisplay, "_NET_SYSTEM_TRAY_ORIENTATION", false);
UpdateManagerWindow (false);
SendDockRequest ();
Screen.RootWindow.AddFilter (filter);
}
protected override void OnUnrealized ()
{
if (manager_window != IntPtr.Zero) {
Gdk.Window gdkwin = Gdk.Window.ForeignNewForDisplay (Display, (uint)manager_window);
if (gdkwin != null) {
gdkwin.RemoveFilter (filter);
}
}
Screen.RootWindow.RemoveFilter (filter);
base.OnUnrealized ();
}
private void UpdateManagerWindow (bool dock_if_realized)
{
IntPtr xdisplay = gdk_x11_display_get_xdisplay (Display.Handle);
if (manager_window != IntPtr.Zero) {
return;
}
XGrabServer (xdisplay);
manager_window = XGetSelectionOwner (xdisplay, selection_atom);
if (manager_window != IntPtr.Zero) {
XSelectInput (xdisplay, manager_window, EventMask.StructureNotifyMask | EventMask.PropertyChangeMask);
}
XUngrabServer (xdisplay);
XFlush (xdisplay);
if (manager_window != IntPtr.Zero) {
Gdk.Window gdkwin = Gdk.Window.ForeignNewForDisplay (Display, (uint)manager_window);
if (gdkwin != null) {
gdkwin.AddFilter (filter);
}
if (dock_if_realized && IsRealized) {
SendDockRequest ();
}
GetOrientationProperty ();
}
}
private void SendDockRequest ()
{
SendManagerMessage (SystemTrayMessage.RequestDock, manager_window, Id, 0, 0);
}
private void SendManagerMessage (SystemTrayMessage message, IntPtr window, uint data1, uint data2, uint data3)
{
XClientMessageEvent ev = new XClientMessageEvent ();
IntPtr display;
ev.type = XEventName.ClientMessage;
ev.window = window;
ev.message_type = (IntPtr)system_tray_opcode_atom;
ev.format = 32;
ev.data.ptr1 = gdk_x11_get_server_time (GdkWindow.Handle);
ev.data.ptr2 = (IntPtr)message;
ev.data.ptr3 = (IntPtr)data1;
ev.data.ptr4 = (IntPtr)data2;
ev.data.ptr5 = (IntPtr)data3;
display = gdk_x11_display_get_xdisplay (Display.Handle);
gdk_error_trap_push ();
XSendEvent (display, manager_window, false, EventMask.NoEventMask, ref ev);
XSync (display, false);
gdk_error_trap_pop ();
}
private FilterReturn ManagerFilter (IntPtr xevent, Event evnt)
{
XEvent xev = (XEvent) Marshal.PtrToStructure (xevent, typeof(XEvent));
if (xev.xany.type == XEventName.ClientMessage
&& (int) xev.xclient.message_type == manager_atom
&& (int) xev.xclient.data.ptr2 == selection_atom) {
UpdateManagerWindow (true);
} else if (xev.xany.window == manager_window) {
if (xev.xany.type == XEventName.PropertyNotify && xev.xproperty.atom == orientation_atom) {
GetOrientationProperty();
} else if (xev.xany.type == XEventName.DestroyNotify) {
ManagerWindowDestroyed();
}
}
return FilterReturn.Continue;
}
private void ManagerWindowDestroyed ()
{
if (manager_window != IntPtr.Zero) {
Gdk.Window gdkwin = Gdk.Window.ForeignNewForDisplay (Display, (uint) manager_window);
if (gdkwin != null) {
gdkwin.RemoveFilter (filter);
}
manager_window = IntPtr.Zero;
UpdateManagerWindow (true);
}
}
private void GetOrientationProperty ()
{
IntPtr display;
int type;
int format;
IntPtr prop_return;
IntPtr nitems, bytes_after;
int error, result;
if (manager_window == IntPtr.Zero) {
return;
}
display = gdk_x11_display_get_xdisplay (Display.Handle);
gdk_error_trap_push ();
type = 0;
result = XGetWindowProperty (display, manager_window, orientation_atom, (IntPtr) 0,
(IntPtr) System.Int32.MaxValue, false, (int) XAtom.Cardinal, out type, out format,
out nitems, out bytes_after, out prop_return);
error = gdk_error_trap_pop ();
if (error != 0 || result != 0) {
return;
}
if (type == (int) XAtom.Cardinal) {
orientation = ((SystemTrayOrientation) Marshal.ReadInt32 (prop_return) == SystemTrayOrientation.Horz)
? Orientation.Horizontal
: Orientation.Vertical;
}
if (prop_return != IntPtr.Zero) {
XFree (prop_return);
}
}
[DllImport ("gdk-x11-2.0")]
private static extern IntPtr gdk_x11_display_get_xdisplay (IntPtr display);
[DllImport ("gdk-x11-2.0")]
private static extern IntPtr gdk_x11_get_server_time (IntPtr window);
[DllImport ("gdk-x11-2.0")]
private static extern void gdk_error_trap_push ();
[DllImport ("gdk-x11-2.0")]
private static extern int gdk_error_trap_pop ();
[DllImport ("libX11", EntryPoint="XInternAtom")]
private extern static int XInternAtom(IntPtr display, string atom_name, bool only_if_exists);
[DllImport ("libX11")]
private extern static void XGrabServer (IntPtr display);
[DllImport ("libX11")]
private extern static void XUngrabServer (IntPtr display);
[DllImport ("libX11")]
private extern static int XFlush (IntPtr display);
[DllImport ("libX11")]
private extern static int XSync (IntPtr display, bool discard);
[DllImport ("libX11")]
private extern static int XFree (IntPtr display);
[DllImport ("libX11")]
private extern static IntPtr XGetSelectionOwner (IntPtr display, int atom);
[DllImport ("libX11")]
private extern static IntPtr XSelectInput (IntPtr window, IntPtr display, EventMask mask);
[DllImport ("libX11", EntryPoint="XSendEvent")]
private extern static int XSendEvent(IntPtr display, IntPtr window, bool propagate, EventMask event_mask,
ref XClientMessageEvent send_event);
[DllImport("libX11")]
private extern static int XGetWindowProperty(IntPtr display, IntPtr w, int property, IntPtr long_offset,
IntPtr long_length, bool deleteProp, int req_type, out int actual_type_return, out int actual_format_return,
out IntPtr nitems_return, out IntPtr bytes_after_return, out IntPtr prop_return);
[Flags]
private enum EventMask {
NoEventMask = 0,
KeyPressMask = 1 << 0,
KeyReleaseMask = 1 << 1,
ButtonPressMask = 1 << 2,
ButtonReleaseMask = 1 << 3,
EnterWindowMask = 1 << 4,
LeaveWindowMask = 1 << 5,
PointerMotionMask = 1 << 6,
PointerMotionHintMask = 1 << 7,
Button1MotionMask = 1 << 8,
Button2MotionMask = 1 << 9,
Button3MotionMask = 1 << 10,
Button4MotionMask = 1 << 11,
Button5MotionMask = 1 << 12,
ButtonMotionMask = 1 << 13,
KeymapStateMask = 1 << 14,
ExposureMask = 1 << 15,
VisibilityChangeMask = 1 << 16,
StructureNotifyMask = 1 << 17,
ResizeRedirectMask = 1 << 18,
SubstructureNotifyMask = 1 << 19,
SubstructureRedirectMask = 1 << 20,
FocusChangeMask = 1 << 21,
PropertyChangeMask = 1 << 22,
ColormapChangeMask = 1 << 23,
OwnerGrabButtonMask = 1 << 24
}
private enum SystemTrayMessage {
RequestDock = 0,
BeginMessage = 1,
CancelMessage = 2
}
private enum SystemTrayOrientation {
Horz = 0,
Vert = 1
}
private enum XEventName {
KeyPress = 2,
KeyRelease = 3,
ButtonPress = 4,
ButtonRelease = 5,
MotionNotify = 6,
EnterNotify = 7,
LeaveNotify = 8,
FocusIn = 9,
FocusOut = 10,
KeymapNotify = 11,
Expose = 12,
GraphicsExpose = 13,
NoExpose = 14,
VisibilityNotify = 15,
CreateNotify = 16,
DestroyNotify = 17,
UnmapNotify = 18,
MapNotify = 19,
MapRequest = 20,
ReparentNotify = 21,
ConfigureNotify = 22,
ConfigureRequest = 23,
GravityNotify = 24,
ResizeRequest = 25,
CirculateNotify = 26,
CirculateRequest = 27,
PropertyNotify = 28,
SelectionClear = 29,
SelectionRequest = 30,
SelectionNotify = 31,
ColormapNotify = 32,
ClientMessage = 33,
MappingNotify = 34,
TimerNotify = 100,
LASTEvent
}
private enum XAtom {
Cardinal = 6,
LASTAtom
}
[StructLayout(LayoutKind.Explicit)]
private struct XEvent
{
[FieldOffset(0)] public XAnyEvent xany;
[FieldOffset(0)] public XPropertyEvent xproperty;
[FieldOffset(0)] public XClientMessageEvent xclient;
}
[StructLayout(LayoutKind.Sequential)]
private struct XAnyEvent
{
internal XEventName type;
internal IntPtr serial;
internal bool send_event;
internal IntPtr display;
internal IntPtr window;
}
[StructLayout(LayoutKind.Sequential)]
private struct XPropertyEvent
{
internal XEventName type;
internal IntPtr serial;
internal bool send_event;
internal IntPtr display;
internal IntPtr window;
internal int atom;
internal IntPtr time;
internal int state;
}
[StructLayout(LayoutKind.Sequential)]
private struct XClientMessageEvent
{
internal XEventName type;
internal IntPtr serial;
internal bool send_event;
internal IntPtr display;
internal IntPtr window;
internal IntPtr message_type;
internal int format;
[StructLayout(LayoutKind.Explicit)]
internal struct DataUnion
{
[FieldOffset(0)] internal IntPtr ptr1;
[FieldOffset(4)] internal IntPtr ptr2;
[FieldOffset(8)] internal IntPtr ptr3;
[FieldOffset(12)] internal IntPtr ptr4;
[FieldOffset(16)] internal IntPtr ptr5;
}
internal DataUnion data;
}
}
#pragma warning restore 0169

Просмотреть файл

@ -0,0 +1,91 @@
using System;
using Gtk;
public class TrayTest
{
private static EventBox event_box;
private static Menu menu;
private static Window window;
public static void Main()
{
Application.Init();
window = new Window("Look at your notification area");
window.DeleteEvent += delegate(object o, DeleteEventArgs args) {
Quit();
args.RetVal = true;
};
window.WindowPosition = WindowPosition.Center;
window.BorderWidth = 50;
window.Add(new Label("Look at your notifcation area"));
window.ShowAll();
// Build the NotificationAreaIcon, pack an event box to handle clicking, etc.
// and pack an icon in the event box to display in the "tray"
NotificationAreaIcon nai_container = new NotificationAreaIcon("Testing");
event_box = new EventBox();
event_box.Add(new Image(Stock.Find, IconSize.Menu));
event_box.ButtonPressEvent += OnNotificationAreaIconButtonPressEvent;
nai_container.Add(event_box);
nai_container.ShowAll();
// Build a menu to show when the user right clicks our icon
menu = new Menu();
foreach(string item in new string [] { "Apples", "Oranges", "Pears", "Grapes", "Apricots", "Plumbs" }) {
menu.Append(new MenuItem(item));
}
menu.Append(new SeparatorMenuItem());
ImageMenuItem quit_item = new ImageMenuItem(Stock.Quit, null);
quit_item.Activated += delegate(object o, EventArgs args) {
Quit();
};
menu.Append(quit_item);
Application.Run();
}
private static void OnNotificationAreaIconButtonPressEvent(object o, ButtonPressEventArgs args)
{
switch(args.Event.Button) {
case 1:
// Show/Hide the main window when user left clicks our icon
window.Visible = !window.Visible;
args.RetVal = true;
return;
case 3:
// Properly position and display a menu when user right clicks our icon
menu.ShowAll();
menu.Popup(null, null, new MenuPositionFunc(PositionMenu), args.Event.Button, args.Event.Time);
args.RetVal = true;
return;
}
args.RetVal = false;
}
// Properly calculate position of menu; takes into account the position of the panel
// containing the NotificationAreaIcon and the edges of the screen
private static void PositionMenu(Menu menu, out int x, out int y, out bool push_in)
{
int button_y, panel_width, panel_height;
Gtk.Requisition requisition = menu.SizeRequest();
event_box.GdkWindow.GetOrigin(out x, out button_y);
(event_box.Toplevel as Gtk.Window).GetSize(out panel_width, out panel_height);
y = (button_y + panel_height + requisition.Height >= event_box.Screen.Height)
? button_y - requisition.Height
: button_y + panel_height;
push_in = true;
}
private static void Quit()
{
Application.Quit();
}
}

Просмотреть файл

@ -0,0 +1,26 @@
<Project name="NotificationAreaIcon" fileversion="2.0" language="C#" ctype="DotNetProject">
<Configurations active="Debug">
<Configuration name="Debug" ctype="DotNetProjectConfiguration">
<Output directory="./" assembly="NotificationAreaIcon" />
<Build debugmode="True" target="Exe" />
<Execution runwithwarnings="True" consolepause="True" runtime="MsNet" />
<CodeGeneration compiler="Csc" warninglevel="4" optimize="True" unsafecodeallowed="False" generateoverflowchecks="True" mainclass="" generatexmldocumentation="False" ctype="CSharpCompilerParameters" />
</Configuration>
<Configuration name="Release" ctype="DotNetProjectConfiguration">
<Output directory="./" assembly="NotificationAreaIcon" />
<Build debugmode="False" target="Exe" />
<Execution runwithwarnings="True" consolepause="True" runtime="MsNet" />
<CodeGeneration compiler="Csc" warninglevel="4" optimize="True" unsafecodeallowed="False" generateoverflowchecks="True" mainclass="" generatexmldocumentation="False" ctype="CSharpCompilerParameters" />
</Configuration>
</Configurations>
<DeploymentInformation strategy="File">
<excludeFiles />
</DeploymentInformation>
<Contents>
<File name="./NotificationAreaIcon.cs" subtype="Code" buildaction="Compile" />
<File name="./Sample.cs" subtype="Code" buildaction="Compile" />
</Contents>
<References>
<ProjectReference type="Gac" localcopy="True" refto="gtk-sharp, Version=2.4.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f" />
</References>
</Project>