initial checkin of yaulw (locally)

This commit is contained in:
Donald Duck
2016-02-15 12:32:26 -05:00
commit 857eda29e3
115 changed files with 27392 additions and 0 deletions

319
WPF/KeepHidden.cs Normal file
View File

@@ -0,0 +1,319 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Threading;
using System.Timers;
using Yaulw.Thread;
namespace Yaulw.WPF
{
/// <remarks>
/// Class used to keep WPF Windows Hidden permanently.
/// This should ideally be called in the Constructor of a window you want to keep hidden.
/// <example>
/// <code>
/// private static KeepHidden _HiddenWindow = null;
/// public HiddenMainWindow()
/// {
/// // * Force this window to remain hidden indefinitly*
/// _HiddenWindow = new KeepHidden(this);
/// }
/// </code>
/// </example>
/// </remarks>
public class KeepHidden
{
#region Private Statics
// Static Map of All our Hidden Windows
private static Dictionary<IntPtr, Window> s_hWndToWindowMap = new Dictionary<IntPtr, Window>();
private static List<Window> s_WindowList = new List<Window>();
private Window _wpfWindow = null;
private object _lockObj = new Object();
#endregion
#region Public Properties
/// <summary>
/// Get the WPF Object That is bound to this Keep Hidden Instance
/// </summary>
public Window wpfWindow { get { return _wpfWindow; } }
/// <summary>
/// Get the HWND Handle to the WPF Object bound to this Keep Hidden Instance
/// </summary>
public IntPtr hwndWindow
{
get
{
if (_wpfWindow != null)
{
WindowInteropHelper interop = new WindowInteropHelper(_wpfWindow);
return interop.Handle;
}
return IntPtr.Zero;
}
}
#endregion
#region Construction
/// <summary>
/// When Passing in a Wpf Window in this Construction, it will ensure that
/// This Window will remain hidden during it's life span. If the Window is Not Loaded
/// yet, call KeepHidden's Show() method to show it, after construction.
/// </summary>
/// <param name="wpfWindow">a WPF Window Object that you want to keep Hidden</param>
public KeepHidden(Window wpfWindow)
{
if (wpfWindow != null && !wpfWindow.IsLoaded)
{
// Assign the Load Event Handler we care about
wpfWindow.Loaded += new RoutedEventHandler(wpfWindow_Loaded);
}
else if (wpfWindow != null && wpfWindow.IsLoaded)
{
// Call the Loaded Event Handler Directly
wpfWindow_Loaded((object)wpfWindow, null);
}
else
throw new ArgumentException("Please pass valid WPF Window Object");
// Make sure we aren't already tracking this window
if (s_WindowList.Contains(wpfWindow))
throw new ArgumentException("WPF Window Object already Kept Hidden");
// Assign remaining stuff
wpfWindow.Closing += new System.ComponentModel.CancelEventHandler(wpfWindow_Closing);
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
_wpfWindow = wpfWindow;
// Add to WPF Window List
s_WindowList.Add(wpfWindow);
// Call this upon construction ~Done Way before Show() get's called
HideWPFWindow(_wpfWindow);
}
#endregion
#region Public Methods
/// <summary>
/// Call this to execute a Show() call on the WPF Window that you want to Keep Hidden
/// </summary>
public void Show()
{
if (_wpfWindow != null && !_wpfWindow.IsLoaded)
{
lock (_lockObj)
{
// Make sure it can't be seen or interacted with
HideWPFWindow(_wpfWindow);
// Show it
_wpfWindow.Show();
// Again... make sure...
HideWPFWindow(_wpfWindow);
// Hide it immediatly, make sure it can't be interacted with
_wpfWindow.Hide();
}
}
}
/// <summary>
/// Call this to execute a Show() call on the WPF Window that you want to Keep Hidden
/// ~However, it will delay call the show allowing the hidden window's constructor to finish
/// </summary>
/// <param name="nDelayInMilliseconds">Milliseconds to delay show the HiddenWindow (at least 250 recommended)</param>
public void Show(uint nDelayInMilliseconds)
{
// Calling Show() directly in the Constructor causes a .Net Run-time Crash
// upon first launch only. Calling it .5 seconds later does the trick of avoiding that error,
// because by then the object is fully constructed
ElapsedEventHandler DelayShowHiddenWindow = delegate(object sender, ElapsedEventArgs e)
{
Timer timer = (Timer)sender;
timer.Stop();
// * Show the Hidden Window *
Show();
timer.Dispose();
timer = null;
};
TTimerDisp timerDelayShowHiddenWindow = new TTimerDisp(DelayShowHiddenWindow, (int) nDelayInMilliseconds, true);
}
/// <summary>
/// Call this to execute a Close() call on the WPF Window that you previously had hidden
/// ~Should only call this when you are done with the Keep Hidden Object
/// </summary>
public void Close()
{
if (_wpfWindow != null && _wpfWindow.IsLoaded)
{
_wpfWindow.Close();
_wpfWindow = null;
}
}
#endregion
#region Public Static Methods
/// <summary>
/// Call this function to determine if the passed in Window is a Hidden Window Object * Tracked by KeepHidden *
/// </summary>
/// <param name="_wpfWindow">pass in a wpf window object to check</param>
/// <returns></returns>
public static bool IsHiddenWindow(Window _wpfWindow)
{
if (_wpfWindow != null)
{
bool bIsFound = s_WindowList.Contains(_wpfWindow);
return bIsFound;
}
return false;
}
#endregion
#region Private Keep Hidden Event Handlers
/// <summary>
/// Called by the WPFWindow's OnLoad Event
/// </summary>
private void wpfWindow_Loaded(object sender, RoutedEventArgs e)
{
lock (_lockObj)
{
Window wpfWindow = (Window)sender;
HideWPFWindow(wpfWindow);
// Add Window Source Message Hook * We'll track the hWnd for the Message Hook
// vie s_hWndToWindowMap
WindowInteropHelper interop = new WindowInteropHelper(wpfWindow);
s_hWndToWindowMap[interop.Handle] = wpfWindow;
HwndSource source = HwndSource.FromHwnd(interop.Handle);
source.AddHook(new HwndSourceHook(MessageHook));
}
}
/// <summary>
/// Called by the WPFWindow's Closing Event
/// </summary>
private void wpfWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
lock (_lockObj)
{
// Delete from the hWndMap, so Message Hook
// Stops processing messages
Window wpfWindow = (Window)sender;
if (s_hWndToWindowMap.ContainsValue(wpfWindow))
{
foreach (IntPtr hWnd in s_hWndToWindowMap.Keys)
{
if (s_hWndToWindowMap[hWnd] == wpfWindow)
{
s_hWndToWindowMap.Remove(hWnd);
break;
}
}
}
// * Imp * Delete internal wpfWindow Reference,
// but DON'T Delete from the s_WindowList. Caller could still call IsHiddenWindow(),
// and we MUST return true if it is
_wpfWindow = null;
}
}
/// <summary>
/// Called by the Process Exiting * We want this to happen last *
/// This allows all unload events for each window to happen first
/// </summary>
void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
// Make sure to clear all windows
s_hWndToWindowMap.Clear();
// Make sure to clear all windows
s_WindowList.Clear();
}
/// <summary>
/// This Message Hook is for the WpfWindow to absolutely ensure that it remains Hidden.
/// We want to make sure that it is never displayed *It can occur that explorer.exe can show it, without this hook*
/// ~i.e. when explorer.exe crashes, and get's restarted, it can cause inconsitencies
/// </summary>
private IntPtr MessageHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// Get the Proper WPF Object and make sure it is Hidden
if (s_hWndToWindowMap.ContainsKey(hwnd))
{
Window wpfWindow = s_hWndToWindowMap[hwnd];
if (wpfWindow != null)
HideWPFWindow(wpfWindow);
}
handled = false;
return System.IntPtr.Zero;
}
#endregion
#region Private Hide Window Functionality
/// <summary>
/// * Core * 'Hiding' Function. Makes sure that the Window is and
/// stays hidden.
/// </summary>
/// <remarks>
/// Height="2" Width="2" AllowsTransparency="True" Background="{x:Null}" WindowStyle="None" WindowStartupLocation="Manual" WindowState="Normal" ResizeMode="NoResize" Foreground="{x:Null}" ShowInTaskbar="False" ShowActivated="False" Left="0" Top="0" MaxWidth="2" MaxHeight="2" MinHeight="2" MinWidth="2" Visibility="Hidden" Opacity="0" IsHitTestVisible="False" IsTabStop="False" Focusable="False" IsEnabled="False"
/// </remarks>
/// <param name="wpfWindow">a WPF window object</param>
private void HideWPFWindow(Window wpfWindow)
{
// Force a tiny Window in top-left corner
wpfWindow.Width = 2;
wpfWindow.Height = 2;
wpfWindow.MinWidth = 2;
wpfWindow.MinHeight = 2;
wpfWindow.MaxWidth = 2;
wpfWindow.MaxHeight = 2;
wpfWindow.Top = 0;
wpfWindow.Left = 0;
// Force transparency
if (!wpfWindow.IsLoaded) // must not be already loaded
wpfWindow.AllowsTransparency = true;
wpfWindow.Background = null;
wpfWindow.Foreground = null;
// Force no user interaction
wpfWindow.WindowStartupLocation = WindowStartupLocation.Manual;
wpfWindow.WindowState = WindowState.Normal;
wpfWindow.ResizeMode = ResizeMode.NoResize;
wpfWindow.ShowInTaskbar = false;
wpfWindow.ShowActivated = false;
wpfWindow.Visibility = Visibility.Hidden;
wpfWindow.IsHitTestVisible = false;
wpfWindow.IsTabStop = false;
wpfWindow.Focusable = false;
// Force Opacity
wpfWindow.WindowStyle = WindowStyle.None;
wpfWindow.Opacity = 0.0;
}
#endregion
}
}

156
WPF/Snippets.cs Normal file
View File

@@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Interop;
namespace Yaulw.WPF
{
/// <remarks>
/// Useful WPF Snippets
/// </remarks>
static public class Snippets
{
/// <summary>
/// Useful to create a simple wrapping tooltip for a wpf control
/// </summary>
/// <param name="strToolTipContent"></param>
/// <param name="height">Set to 0 to leave default, else set to 0> to define max height</param>
/// <param name="width">Set to 0 to leave default, else set to 0> to define max width</param>
/// <returns>a ToolTip Object to assign to a control</returns>
public static ToolTip CreateNewStringToolTip(string strToolTipContent, int height, int width)
{
// Create the TextBlock
TextBlock tx = new TextBlock();
if (height > 0)
tx.Height = height;
if (width > 0)
tx.Width = width;
tx.TextWrapping = TextWrapping.Wrap;
tx.Text = strToolTipContent;
// Create the ToolTip with the TextBlock inside
ToolTip tt = new ToolTip();
tt.Content = strToolTipContent;
return tt;
}
/// <summary>
/// Useful if you want to know if the Mouse cursor is over the specified Wpf Window
/// (Uses windowsforms to do the calculations)
/// </summary>
/// <returns>true if the mouse cursor is over the specified form window, false otherwise</returns>
public static bool IsMouseCursorOverWPFormWindow(Window wpfWindow)
{
if (wpfWindow != null)
{
// Get the Point location of the mouse cursor
System.Drawing.Point point = System.Windows.Forms.Cursor.Position;
// Get the rect for the Navigation Form
Point wpfFormLeftTopPoint = new Point(wpfWindow.Left, wpfWindow.Top);
Size wpfFormSize = new Size(wpfWindow.Width, wpfWindow.Height);
Rect rect = new Rect(wpfFormLeftTopPoint, wpfFormSize);
// Return if the Mouse is over the Navigation Form
return (rect.Contains((double)point.X, (double)point.Y));
}
return false;
}
/// <summary>
/// For Dynamically Creating Text ComboBox Items
/// </summary>
/// <param name="strContent">Text Content to Display</param>
/// <param name="tag">object to tag to the menu item</param>
/// <returns></returns>
public static ComboBoxItem CreateAComboBoxItem(string strContent, object tag)
{
if (!String.IsNullOrEmpty(strContent) && (tag != null))
{
ComboBoxItem item = new ComboBoxItem();
item.Content = strContent;
item.Tag = tag;
return item;
}
return null;
}
/// <summary>
/// For dynamically creating Image sources, this function helps you to create an image out of
/// a Resource Uri. You can then assign this image to a 'Source' property on an image wpf object
/// </summary>
/// <param name="strRelativeResourceUri">a valid relative Resource Uri String to an image</param>
/// <param name="ImageHeight">the output image's desired height</param>
/// <param name="ImageWidth">the output image's desired width</param>
/// <returns></returns>
public static Image CreateWPFImageFromRelativeResourceUri(string strRelativeResourceUri, int ImageHeight, int ImageWidth)
{
if (!String.IsNullOrEmpty(strRelativeResourceUri))
{
Image myImage = new Image();
BitmapImage image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(strRelativeResourceUri, UriKind.Relative);
image.EndInit();
myImage.Stretch = Stretch.Fill;
myImage.Height = ImageHeight;
myImage.Width = ImageWidth;
myImage.Source = image;
return myImage;
}
return null;
}
/// <summary>
/// Uses the InteropHelper to get the Handle of a WPF Window
/// </summary>
/// <param name="window">a WPF Window</param>
/// <returns>an hWnd for the specified WPF Window</returns>
public static IntPtr GetHandleForWPFWindow(Window window)
{
WindowInteropHelper InteropHelper = new WindowInteropHelper(window);
if (InteropHelper.Handle != IntPtr.Zero)
return InteropHelper.Handle;
#if NET4
else
return InteropHelper.EnsureHandle();
#else
else
return IntPtr.Zero;
#endif
}
/// <summary>
/// Uses the InteropHelper to set the Owner Property of a WPF Window
/// </summary>
/// <param name="window">a WPF Window</param>
/// <param name="hOwnerWnd">Owner hWnd Handle to set for WPF Window</param>
public static void SetOwnerForWPFWindow(Window window, IntPtr hOwnerWnd)
{
WindowInteropHelper InteropHelper = new WindowInteropHelper(window);
InteropHelper.Owner = hOwnerWnd;
}
/// <summary>
/// Adds the Specified Message Hook the the specified WPF Window.
/// Ensures that the WPF Window exists (must be loaded with valid hWnd).
/// </summary>
/// <param name="window">a WPF Window</param>
/// <param name="hook">a message hook function</param>
public static void SetMessageHookForWPFWindow(Window window, HwndSourceHook hook)
{
WindowInteropHelper interop = new WindowInteropHelper(window);
#if NET4
HwndSource source = HwndSource.FromHwnd(interop.EnsureHandle());
#else
HwndSource source = HwndSource.FromHwnd(interop.Handle);
#endif
source.AddHook(hook);
}
}
}

232
WPF/WPFWindowManager.cs Normal file
View File

@@ -0,0 +1,232 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using Yaulw.Thread;
using System.Windows;
using Yaulw.Other;
using System.Collections;
using System.Windows.Interop;
namespace Yaulw.WPF
{
/// <summary>
/// Responsible for Managing WPFWindows
/// </summary>
public class WPFWindowManager : WindowManager
{
#region Construction
/// <summary>
/// WPFWindow Manager Contructor
/// </summary>
/// <param name="dispatcher">Thread Dispatcher Object</param>
/// <param name="windowTypes">Window Types this WindowManager is managing</param>
/// <param name="PerformanceLoad">true, to load performance enabled windows upon construction</param>
public WPFWindowManager(Dispatcher dispatcher, WindowType[] windowTypes, bool PerformanceLoad)
: base(dispatcher, windowTypes, PerformanceLoad)
{
// Here i can load Show/hide all windows that are performance loaded * To further load stuff WPF related *
if (PerformanceLoad)
{
foreach (WindowType type in windowTypes)
{
List<object> objects = GetObjects(type);
if (objects.Count == 1 && type.IsPerformanceLoaded)
{
// Show/Hide Window!
}
}
}
}
#endregion
#region Public Overriden Methods
/// <summary>
///
/// </summary>
/// <param name="windowKey">Window to run action on</param>
/// <param name="attributes">Window Attributes to use</param>
/// <param name="tag">object to pass into Window</param>
/// <returns>the tag object from the window</returns>
public override object ShowWindow(Enum windowKey, WindowAttributes attributes, object tag)
{
DelegateCollection.Obj_Func func = delegate()
{
object o = CreateInstance(windowKey);
if (AddObject(windowKey, o))
{
Window wpfWin = (Window)o;
wpfWin.Tag = tag;
// Set Attributes
SetAttributesOnWindow(wpfWin, attributes);
// Show
wpfWin.Show();
object retVal = wpfWin.Tag;
wpfWin = null;
return retVal;
}
return null;
};
if (Dispatcher.Thread == System.Threading.Thread.CurrentThread)
{
return func();
}
else
{
object[] parameters = new object[] { windowKey, attributes, tag };
return Dispatcher.Invoke((ShowDelegate)ShowWindow, DispatcherPriority.Normal, parameters);
}
}
/// <summary>
/// Show the WPF Window as a Dialog
/// </summary>
/// <param name="windowKey">Window to run action on</param>
/// <param name="attributes">Window Attributes to use</param>
/// <param name="tag">object to pass into Window</param>
/// <returns>the tag object from the window</returns>
public override object ShowDialog(Enum windowKey, WindowAttributes attributes, object tag)
{
DelegateCollection.Obj_Func func = delegate()
{
object o = CreateInstance(windowKey);
if (AddObject(windowKey, o))
{
Window wpfWin = (Window)o;
wpfWin.Tag = tag;
// Set Attributes
SetAttributesOnWindow(wpfWin, attributes);
// ShowDialog()
wpfWin.ShowDialog();
object retVal = wpfWin.Tag;
DeleteObject(windowKey);
wpfWin = null;
return retVal;
}
return null;
};
if (Dispatcher.Thread == System.Threading.Thread.CurrentThread)
{
return func();
}
else
{
object[] parameters = new object[] { windowKey, attributes, tag };
return Dispatcher.Invoke((ShowDelegate)ShowDialog, DispatcherPriority.Normal, parameters);
}
}
/// <summary>
/// Run any generic action on a window
/// </summary>
/// <param name="windowKey">Window to run action on</param>
/// <param name="action">action to perform on the windo</param>
public override bool RunAction(Enum windowKey, DelegateCollection.Bool_Param1_Window_Func action)
{
if (Dispatcher.Thread == System.Threading.Thread.CurrentThread)
{
List<object> objects = GetObjects(windowKey);
object o = null;
if (objects != null)
o = objects.Last();
if (o != null && o is Window && action != null)
return action((Window)o);
else
return action(null);
}
else
{
object[] parameters = new object[] { windowKey, action };
return (bool)Dispatcher.Invoke((ActionDelegate)RunAction, DispatcherPriority.Normal, parameters);
}
}
/// <summary>
/// Hide the Specified Window
/// </summary>
/// <param name="windowKey">Window to run action on</param>
/// <returns>true, if successful, false otherwise</returns>
public override bool HideWindow(Enum windowKey)
{
DelegateCollection.Bool_Param1_Window_Func func = delegate(Window wpfWin)
{
wpfWin.Hide();
return true;
};
return RunAction(windowKey, func);
}
/// <summary>
/// Close the Specified Window
/// </summary>
/// <param name="windowKey">Window to run action on</param>
/// <returns>true, if successful, false otherwise</returns>
public override bool CloseWindow(Enum windowKey)
{
DelegateCollection.Bool_Param1_Window_Func func = delegate(Window wpfWin)
{
DeleteObject(windowKey);
return true;
};
return RunAction(windowKey, func);
}
/// <summary>
/// Dispose of this manager Properly
/// </summary>
public override void Dispose()
{
// We must call the base's ClearAllObjects()
DelegateCollection.Bool_Param1_Window_Func func = delegate(Window wpfWin)
{
ClearAllObjects();
return true;
};
RunAction(null, func);
}
#endregion
#region Private Helpers
/// <summary>
/// Set the Window Attributes as specifed by the WindowAttributes type
/// </summary>
/// <param name="attributes">Attributes to set</param>
/// <param name="wpfWin">Window to set them on</param>
private void SetAttributesOnWindow(Window wpfWin, WindowAttributes attributes)
{
// Set Attributes
if (attributes != null && wpfWin != null)
{
WindowInteropHelper InteropHelper = new WindowInteropHelper(wpfWin);
if (attributes.hWndOwner != IntPtr.Zero)
InteropHelper.Owner = (IntPtr)attributes.hWndOwner;
if (attributes.Height != 0)
wpfWin.Height = attributes.Height;
if (attributes.Width != 0)
wpfWin.Width = attributes.Width;
if (attributes.Left != int.MinValue)
wpfWin.Left = attributes.Left;
if (attributes.Top != int.MinValue)
wpfWin.Top = attributes.Top;
if (!String.IsNullOrEmpty(attributes.Title))
wpfWin.Title = attributes.Title;
}
}
#endregion
}
}