⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 notify.cs

📁 本源码为OpenNETCF源代码
💻 CS
📖 第 1 页 / 共 2 页
字号:
//==========================================================================================
//
//		OpenNETCF.Win32.Notify
//		Copyright (c) 2003-2005, OpenNETCF.org
//
//		This library is free software; you can redistribute it and/or modify it under 
//		the terms of the OpenNETCF.org Shared Source License.
//
//		This library is distributed in the hope that it will be useful, but 
//		WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
//		FITNESS FOR A PARTICULAR PURPOSE. See the OpenNETCF.org Shared Source License 
//		for more details.
//
//		You should have received a copy of the OpenNETCF.org Shared Source License 
//		along with this library; if not, email licensing@opennetcf.org to request a copy.
//
//		If you wish to contact the OpenNETCF Advisory Board to discuss licensing, please 
//		email licensing@opennetcf.org.
//
//		For general enquiries, email enquiries@opennetcf.org or visit our website at:
//		http://www.opennetcf.org
//
//==========================================================================================
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using OpenNETCF.Runtime.InteropServices;

namespace OpenNETCF.Win32.Notify
{
	#region Notify
	/// <summary>
	/// Contains Notification related Methods
	/// </summary>
	public class Notify
	{		
		private Notify(){}

		#region Run App At Event
		/// <summary>   
		/// This function starts running an application when a specified event occurs.   
		/// </summary>   
		/// <param name="appName">Name of the application to be started.</param>   
		/// <param name="whichEvent">Event at which the application is to be started.</param>   
		/// <seealso cref="T:OpenNETCF.Win32.Core.EventNotifications"/>   
		public static void RunAppAtEvent(string appName, NotificationEvent whichEvent)   
		{   
			if(!CeRunAppAtEvent(appName, (int)whichEvent))   
			{   
				throw new WinAPIException("Cannot Set Notification Handler");   
			}   
		} 
		#endregion
    
		#region Run App At Time
		/// <summary>   
		/// This function prompts the system to start running a specified application at a specified time.   
		/// </summary>   
		/// <param name="appName">Name of the application to be started.</param>   
		/// <param name="time">DateTime at which to run application.</param>
		/// <remarks>To cancel an existing RunAppATime request pass the application name and DateTime.MinValue</remarks>
		public static void RunAppAtTime(string appName, System.DateTime time)   
		{   
			byte[] timebytes;

			if(time==System.DateTime.MinValue)
			{
				//cancel request pass null
				timebytes = null;
			}
			else
			{
				//get native system time struct
				SystemTime st = SystemTime.FromDateTime(time);
				//get bytes
				timebytes = st.ToByteArray();
			}

			if(!CeRunAppAtTime(appName, timebytes))   
			{   
				throw new WinAPIException("Cannot Set Notification Handler");   
			}  
		}   
		#endregion

		#region Set User Notification
		/// <summary>
		/// Creates a new user notification.
		/// </summary>
		/// <param name="application">String that specifies the name of the application that owns this notification.</param>
		/// <param name="time">The time when the notification should occur.</param>
		/// <param name="notify">Notification object that describes the events that are to occur when the notification time is reached.</param>
		/// <returns>The handle to the notification indicates success.</returns>
		public static int SetUserNotification(string application, System.DateTime time, UserNotification notify)
		{
			return SetUserNotification(0, application, time, notify);
		}
		/// <summary>
		/// Edit an existing user notification.
		/// </summary>
		/// <param name="handle">Handle to the notification to overwrite.</param>
		/// <param name="application">String that specifies the name of the application that owns this notification.</param>
		/// <param name="time">The time when the notification should occur.</param>
		/// <param name="notify">Notification object that describes the events that are to occur when the notification time is reached.</param>
		/// <returns>The handle to the notification indicates success.</returns>
		public static int SetUserNotification(int handle, string application, System.DateTime time, UserNotification notify)
		{
			//call api function
			int outhandle = CeSetUserNotification(handle, application, SystemTime.FromDateTime(time).ToByteArray(), notify.ToByteArray()); 
			
			//if invalid handle throw exception
			if(outhandle==0)
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(),"Error setting UserNotification");
			}
			return outhandle;
		}
		/// <summary>
		/// This function creates a new user notification.
		/// </summary>
		/// <param name="trigger">A UserNotificationTrigger that defines what event activates a notification.</param>
		/// <param name="notification">A UserNotification that defines how the system should respond when a notification occurs.</param>
		/// <returns>Handle to the notification event if successful.</returns>
		public static int SetUserNotification(UserNotificationTrigger trigger, UserNotification notification)
		{
			byte[] notifybytes = null;
			if(notification!=null)
			{
				notifybytes = notification.ToByteArray();
			}

			int outhandle = CeSetUserNotificationEx(0, trigger.ToByteArray(), notifybytes);
			
			//throw on invalid handle
			if(outhandle==0)
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(),"Error setting UserNotification");
			}
			return outhandle;
		}
		/// <summary>
		/// This function modifies an existing user notification.
		/// </summary>
		/// <param name="handle">Handle of the Notification to be modified</param>
		/// <param name="trigger">A UserNotificationTrigger that defines what event activates a notification.</param>
		/// <param name="notification">A UserNotification that defines how the system should respond when a notification occurs.</param>
		/// <returns>Handle to the notification event if successful.</returns>
		public static int SetUserNotification(int handle, UserNotificationTrigger trigger, UserNotification notification)
		{
			int outhandle = CeSetUserNotificationEx(handle, trigger.ToByteArray(), notification.ToByteArray());
			
			//throw on invalid handle
			if(outhandle==0)
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(), "Error setting UserNotification");
			}
			return outhandle;
		}
		#endregion

		#region Clear User Notification
		/// <summary>
		/// Deletes a registered user notification that was created by a previous call to the SetUserNotification function.
		/// </summary>
		/// <param name="handle">Handle to the user notification to delete.</param>
		/// <returns>TRUE indicates success. FALSE indicates failure.</returns>
		/// <remarks>ClearNotification does not operate on notifications that have occurred.</remarks>
		public static bool ClearUserNotification(int handle)
		{
			return CeClearUserNotification(handle);
		}
		#endregion

		#region Get User Notification
		/// <summary>
		/// Retrieves notification information associated with a handle.
		/// </summary>
		/// <param name="handle">Handle to the user notification to retrieve.</param>
		/// <returns>The requested UserNotification.</returns>
		public static UserNotificationInfoHeader GetUserNotification(int handle)
		{
			//buffer size
			int size = 0;

			//first query for buffer size required
			CeGetUserNotification(handle, 0, ref size, IntPtr.Zero);

			//create a marshallable buffer
			IntPtr buffer = MarshalEx.AllocHGlobal(size);

			//call native getter
			if(!CeGetUserNotification(handle, (uint)size, ref size, buffer))
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(), "Error getting UserNotification");
			}

			UserNotificationInfoHeader nih = UserNotificationInfoHeader.FromPtr(buffer);

			//free native memory
			MarshalEx.FreeHGlobal(buffer);

			return nih;
		}
		#endregion

		#region Get User Notification Handles
		/// <summary>
		/// Returns an array of currently stored notifications.
		/// </summary>
		/// <returns>Array of currently stored notifications.</returns>
		public static int[] GetUserNotificationHandles()
		{
			int size = 0;
			//get size required
			if(!CeGetUserNotificationHandles(null, 0, ref size))
			{
				throw new WinAPIException("Error retrieving handles");
			}
			//create array to fill
			int[] handles = new int[size];
			//this time pass the buffer to be filled
			if(!CeGetUserNotificationHandles(handles, size, ref size))
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(), "Error retrieving handles");
			}

			//return populated handles array
			return handles;
		}
		#endregion

		#region Get User Notification Preferences
		/// <summary>
		/// This function queries the user for notification settings by displaying a dialog box showing options that are valid for the current hardware platform.
		/// </summary>
		/// <param name="hWnd">Handle to the parent window for the notification settings dialog box.</param>
		/// <returns>A UserNotification structure containing the user's notification settings.</returns>
		public static UserNotification GetUserNotificationPreferences(IntPtr hWnd)
		{
			UserNotification template = new UserNotification();

			return GetUserNotificationPreferences(hWnd, template);

		}
		/// <summary>
		/// This function queries the user for notification settings by displaying a dialog box showing options that are valid for the current hardware platform.
		/// </summary>
		/// <param name="hWnd">Handle to the parent window for the notification settings dialog box.</param>
		/// <param name="template">UserNotification structure used to populate the default settings.</param>
		/// <returns>A UserNotification structure containing the user's notification settings.</returns>
		public static UserNotification GetUserNotificationPreferences(IntPtr hWnd, UserNotification template)
		{
			template.Sound = new string('\0', 255);

			if(!CeGetUserNotificationPreferences(hWnd, template.ToByteArray()))
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not get user preferences");
			}
			return template;
		}
		#endregion

		#region Handle App Notifications
		/// <summary>
		/// This function marks as "handled" all notifications previously registered by the given application that have occurred.
		/// </summary>
		/// <param name="application">The name of the application whose events are to be marked as "handled".
		/// This must be the name that was passed in to <see cref="M:OpenNETCF.Win32.Notify.Notify.SetUserNotification"/> as the owner of the notification.</param>
		public static void HandleAppNotifications(string application)
		{
			//throw exception on failure
			if(!CeHandleAppNotifications(application))
			{
				throw new Win32Exception(Marshal.GetLastWin32Error(), "Error clearing Application Notifications");
			}
		}
		#endregion
  

		#region Notify P/Invokes

		[DllImport("coredll.dll", EntryPoint="CeRunAppAtEvent", SetLastError=true)]   
		private static extern bool CeRunAppAtEvent(string pwszAppName, int lWhichEvent);   
    
		[DllImport("coredll.dll", EntryPoint="CeRunAppAtTime", SetLastError=true)]   
		private static extern bool CeRunAppAtTime(string pwszAppName, byte[] lpTime);   

		[DllImport("coredll.dll", EntryPoint="CeSetUserNotificationEx", SetLastError=true)]   
		private static extern int CeSetUserNotificationEx(int hNotification, byte[] lpTrigger, byte[] lpUserNotification);

		[DllImport("coredll.dll", EntryPoint="CeSetUserNotification", SetLastError=true)]   
		private static extern int CeSetUserNotification(int hNotification, string pwszAppName, byte[] lpTime, byte[] lpUserNotification);

		[DllImport("coredll.dll", EntryPoint="CeClearUserNotification", SetLastError=true)]   
		private static extern bool CeClearUserNotification(int hNotification);
		
		[DllImport("coredll.dll", EntryPoint="CeGetUserNotification", SetLastError=true)]   
		private static extern bool CeGetUserNotification (int hNotification, uint cBufferSize, ref int pcBytesNeeded, IntPtr pBuffer );

		[DllImport("coredll.dll", EntryPoint="CeGetUserNotificationHandles", SetLastError=true)]   
		private static extern bool CeGetUserNotificationHandles(int[] rghNotifications, int cHandles, ref int pcHandlesNeeded);

		[DllImport("coredll.dll", EntryPoint="CeGetUserNotificationPreferences", SetLastError=true)]   
		private static extern bool CeGetUserNotificationPreferences(IntPtr hWndParent, byte[] lpNotification);

		[DllImport("coredll.dll", EntryPoint="CeHandleAppNotifications", SetLastError=true)]   
		private static extern bool CeHandleAppNotifications(string appName);

		#endregion 
	}
	#endregion

	#region User Notification
	/// <summary>
	/// This structure contains information used to initialize the user notifications settings dialog box, and receives the user抯 notification preferences entered by way of the dialog box.
	/// Also used when setting a user notification. 
	/// </summary>
	public class UserNotification : IDisposable
	{
		private const int Size = 24;
		private byte[] data;

		#region Constructor
		/// <summary>
		/// Create a new instance of the UserNotification class
		/// </summary>
		public UserNotification()
		{
			data = new byte[Size];

			//set maxsound to maxpath * charsize (512)
			BitConverter.GetBytes((int)512).CopyTo(data, 16);
		}
		#endregion

		internal byte[] ToByteArray()
		{
			return data;
		}

		#region From Pointer
		/// <summary>
		/// Returns a UserNotification object from a specified memory location.
		/// </summary>
		/// <param name="data">Pointer to UserNotification in unmanaged memory.</param>
		/// <returns>A new UserNotification object.</returns>
		/// <remarks>This method is used internally and should not be required in normal use.</remarks>
		public static UserNotification FromPtr(IntPtr data)
		{
			//create new notification instance
			UserNotification newnotification = new UserNotification();

			Marshal.Copy(data, newnotification.data, 0, Size);

			return newnotification;
		}
		#endregion


		#region Action
		/// <summary>
		/// Any combination of the <see cref="T:OpenNETCF.Win32.Notify.NotificationAction"/> members.  
		/// </summary>
		/// <value>Flags which specifies the action(s) to be taken when the notification is triggered.</value>
		/// <remarks>Flags not valid on a given hardware platform will be ignored.</remarks>
		public NotificationAction Action
		{
			get
			{
				return (NotificationAction)BitConverter.ToInt32(data, 0);
			}
			set
			{
				BitConverter.GetBytes((int)value).CopyTo(data, 0);
			}
		}
		#endregion

		#region Title
		/// <summary>
		/// Required if NotificationAction.Dialog is set, ignored otherwise
		/// </summary>
		public string Title
		{
			get
			{
				IntPtr titleptr = (IntPtr)BitConverter.ToInt32(data, 4);
				if(titleptr!=IntPtr.Zero)
				{
					return Marshal.PtrToStringUni(titleptr);
				}
				else
				{
					return null;
				}
			}
			set
			{
				IntPtr titleptr = (IntPtr)BitConverter.ToInt32(data, 4);
				
				//free up previous value
				if(titleptr!=IntPtr.Zero)
				{
					MarshalEx.FreeHGlobal(titleptr);
				}
				//marshal string to unmanaged memory
				titleptr = MarshalEx.StringToHGlobalUni(value);
				//store ptr in bytearray
				BitConverter.GetBytes((int)titleptr).CopyTo(data, 4);
			}
		}
		#endregion
		
		#region Text
		/// <summary>
		/// Required if NotificationAction.Dialog is set, ignored otherwise.
		/// </summary>
		public string Text
		{
			get
			{
				IntPtr textptr = (IntPtr)BitConverter.ToInt32(data, 8);

				if(textptr!=IntPtr.Zero)
				{
					return Marshal.PtrToStringUni(textptr);
				}
				else
				{
					return null;
				}
			}
			set
			{
				//free up previous value
				IntPtr textptr = (IntPtr)BitConverter.ToInt32(data, 8);

				if(textptr!=IntPtr.Zero)
				{
					MarshalEx.FreeHGlobal(textptr);
				}
				//marshal string to unmanaged memory
				textptr = MarshalEx.StringToHGlobalUni(value);
				//store ptr in bytearray
				BitConverter.GetBytes((int)textptr).CopyTo(data, 8);			
			}
		}
		#endregion

		#region Sound
		/// <summary>
		/// Sound string as supplied to PlaySound.
		/// </summary>
		/// <remarks>SetUserNotification() ignores it if the <see cref="P:OpenNETCF.Win32.Notify.UserNotification.Action">Action property</see> does not contain <see cref="T:OpenNETCF.Win32.Notify.NotifyAction">NotifyAction.Sound</see>.</remarks>
		public string Sound
		{
			get
			{
				IntPtr soundptr = (IntPtr)BitConverter.ToInt32(data, 12);

				if(soundptr!=IntPtr.Zero)
				{
					return Marshal.PtrToStringUni(soundptr);
				}
				else
				{
					return null;
				}
			}
			set
			{
				//free up previous value
				IntPtr soundptr = (IntPtr)BitConverter.ToInt32(data, 12);

				if(soundptr!=IntPtr.Zero)
				{
					MarshalEx.FreeHGlobal(soundptr);
				}
				//marshal string to unmanaged memory
				soundptr = MarshalEx.StringToHGlobalUni(value);
				//store ptr in bytearray
				BitConverter.GetBytes((int)soundptr).CopyTo(data, 12);
			}
		}
		#endregion

		#region Max Sound
		/// <summary>
		/// Maximum length of sound parameter.
		/// </summary>
		public int MaxSound

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -