Drag & Drop for SpecialFolders - wpf

I have an application that allows users to drag and drop files or entire folders into a special "drop area," at which point all files are processed. The application is being developed using WPF, and this particular XAML view sets "AllowDrop" to true and handles the Drop event in code-behind.
Everything is working for normal files and standrard Windows folders. However, if the user drops a special Windows folder (e.g., Pictures, Videos), then the functionality does not work. It would appear this is because the contents of DragEventArgs.Data are not a DataFormats.FileDrop enum. That's not the case with other folders or files.
My code for handling the drop, in part, is:
private void OnDrop(object Sender, DragEventArgs E)
{
if (E.Data.GetDataPresent(DataFormats.FileDrop))
{
var _droppedFilePaths = E.Data.GetData(DataFormats.FileDrop, true) as string[];
// Process the files....
}
}
Is there any way to identify that the drop data contains the Windows 7 pictures library and map back to its actual path?

Using the solution described here, I wrote the following method:
const string ShellIdListArrayName = "Shell IDList Array";
static IEnumerable<string> GetPathsFromShellIDListArray(IDataObject data)
{
if (data.GetDataPresent(ShellIdListArrayName))
{
var ms = (MemoryStream)data.GetData(ShellIdListArrayName);
byte[] bytes = ms.ToArray();
IntPtr p = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, p, bytes.Length);
uint cidl = (uint)Marshal.ReadInt32(p, 0);
int offset = sizeof(uint);
IntPtr parentpidl = (IntPtr)((int)p + (uint)Marshal.ReadInt32(p, offset));
StringBuilder path = new StringBuilder(256);
SHGetPathFromIDList(parentpidl, path);
for (int i = 1; i <= cidl; ++i)
{
offset += sizeof(uint);
IntPtr relpidl = (IntPtr)((int)p + (uint)Marshal.ReadInt32(p, offset));
IntPtr abspidl = ILCombine(parentpidl, relpidl);
if (SHGetPathFromIDList(abspidl, path) != 0)
{
yield return path.ToString();
}
ILFree(abspidl);
}
}
}
[DllImport("shell32.dll")]
public static extern int SHGetPathFromIDList(IntPtr pidl, StringBuilder pszPath);
[DllImport("shell32.dll")]
public static extern IntPtr ILCombine(IntPtr pidl1, IntPtr pidl2);
[DllImport("shell32.dll")]
public static extern void ILFree(IntPtr pidl);
You can just pass e.Data from your event handler to this method, and you will get a sequence of paths (assuming the items do have a path of course... for instance, "My computer" doesn't have a path)

Related

How can I know whether a form is showing to user?

I have a system monitor program which cost system resource heavly. I hope the program run tasks only when the form is showing to users. One way is to check whether the form is foreground window or active window.
But if the form is not activated but is showing to users (for example, you can see two windows in following picture, one of the window is not activated but showing to users), I can't handle the situation well.
window example http://www.chip.de/ii/117599040_a933fb45fe.gif
Any ideas? Thanks in advanced.
Edit:
I have found the solution according to my colleague's suggest.
Here is my solution:
enum GetWindow_Cmd : uint
{
GW_HWNDFIRST = 0,
GW_HWNDLAST = 1,
GW_HWNDNEXT = 2,
GW_HWNDPREV = 3,
GW_OWNER = 4,
GW_CHILD = 5,
GW_ENABLEDPOPUP = 6
}
[DllImport("user32.dll", SetLastError = true)]
static extern bool IsZoomed(IntPtr hwnd);
[DllImport("user32.dll", SetLastError = true)]
static extern bool IsWindowVisible(IntPtr hwnd);
[DllImport("user32.dll", EntryPoint = "GetWindow", SetLastError = true)]
static extern IntPtr GetNextWindow(IntPtr hWnd, uint cmd);
[DllImport("user32.dll", EntryPoint = "GetWindowText", SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount);
[DllImport("user32.dll", EntryPoint = "GetForegroundWindow")]
private static extern IntPtr GetForegroundWindow();
//I have made some simplifications. My form is maximized. If the form is not
// maximized, you should calculate the region of current form and top level form
// to check it.
private bool IsShowing()
{
if(this.Visible == false || this.WindowState = FormWindowState.Minimized)
return false;
IntPtr currentHandler = this.Handle;
if (currentHandler == GetForegroundWindow())
return true;
while (currentHandler != GetForegroundWindow())
{
IntPtr hwnd = GetNextWindow(currentHandler, (uint)GetWindow_Cmd.GW_HWNDPREV);
currentHandler = hwnd;
if (IsZoomed(currentHandler) && IsWindowVisible(currentHandler))
{
StringBuilder sb = new StringBuilder(255);
GetWindowText(currentHandler, sb, sb.Capacity + 1);
Debug.WriteLine("masked by:" + sb.ToString());
return false;
}
}
if (IsZoomed(currentHandler) && IsWindowVisible(currentHandler))
{
StringBuilder sb = new StringBuilder(255);
GetWindowText(currentHandler, sb, sb.Capacity + 1);
Debug.WriteLine("masked by:" + sb.ToString());
return false;
}
return true;
}
It is not clear when you want to run or not your tasks, but in any case, I think that the best approach is to let the system notify you when your form acvtive or visible state changes. In this case you should write the activation and deactivation tasks's code in the forms event Activated, Deactivate and/or VisibleChanged
From MSDN
Deactivate: Occurs when the form loses focus and is no longer the
active form.
Activated: Occurs when the form is activated in code or by the user.
VisibleChanged: Occurs when the Visible property value changes.
You could also find useful to refer to this article that shows the order of events in the loading and closing of a form

How to turn off all touch input at application, window or control level?

Using c# for a wpf application, if in Windows 7 touch is enabled in the control panel, a user by default can 'write' on an InkCanvas with a finger. I want to disable that and force stylus input only.
I'd like to know how to do it more than one way if possible: first by disabling touch on the InkCanvas, second by disabling it for a particular window, and third by disabling it for the entire application. A bonus fourth would be knowing how to turn touch on or off system-wide.
I have tried UnregisterTouchWindow, and I have tried setting Stylus.SetIsTouchFeedbackEnabled to false for the InkCanvas, but neither has worked.
Further digging helped me put together the following as a way to toggle touch on/off system-wide. If anyone knows how to accomplish this in any of the other 3 ways, I'd still appreciate those answers.
The basic steps are to check the current registry status, change it if necessary (and then refresh the system to recognize the change), and make note of the initial state to restore if needed on program exit.
Thanks to the posters at these two links for the education.
public MainWindow(){
InitializeComponent();
RegistryKey regKey = Registry.CurrentUser;
regKey = regKey.OpenSubKey(#"Software\Microsoft\Wisp\Touch", true);
string currKey = regKey.GetValue("TouchGate").ToString();
if (currKey == "1")
{
regKey.SetValue("TouchGate", 0x00000000);
User32Utils.Notify_SettingChange();
UserConfig.TGate = "1";
}
regKey.Close();
...
}
public static class UserConfig {
public static string TGate { get; set; }
...
}
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e){
...
if (UserConfig.TGate == "1")
{
RegistryKey regKey = Registry.CurrentUser;
regKey = regKey.OpenSubKey(#"Software\Microsoft\Wisp\Touch", true);
regKey.SetValue("TouchGate", 0x00000001);
User32Utils.Notify_SettingChange();
regKey.Close();
}
}
//------------------User32Utils.cs
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace (...)
{
internal class User32Utils
{
#region USER32 Options
static IntPtr HWND_BROADCAST = new IntPtr(0xffffL);
static IntPtr WM_SETTINGCHANGE = new IntPtr(0x1a);
#endregion
#region STRUCT
enum SendMessageTimeoutFlags : uint
{
SMTO_NORMAL = 0x0000,
SMTO_BLOCK = 0x0001,
SMTO_ABORTIFHUNG = 0x2,
SMTO_NOTIMEOUTIFNOTHUNG = 0x0008
}
#endregion
#region Interop
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern IntPtr SendMessageTimeout(IntPtr hWnd,
uint Msg,
UIntPtr wParam,
UIntPtr lParam,
SendMessageTimeoutFlags fuFlags,
uint uTimeout,
out UIntPtr lpdwResult);
#endregion
internal static void Notify_SettingChange()
{
UIntPtr result;
SendMessageTimeout(HWND_BROADCAST, (uint)WM_SETTINGCHANGE,
UIntPtr.Zero, UIntPtr.Zero,
SendMessageTimeoutFlags.SMTO_NORMAL, 1000, out result);
}
}
}

Subscribing to mouse events of all controls in form

How can i easily catch the "mouse down" events of all the controls in a form, without manually subscribing to each and every event? (C#)
Something like the "KeyPreview" feature, but for the mouse events.
I found this to be the best solution for my purposes.
Create a new class derived from IMessageFilter:
public class GlobalMouseHandler : IMessageFilter
{
private const int WM_LBUTTONDOWN = 0x201;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_LBUTTONDOWN)
{
// do something
((YourMainForm)Form.ActiveForm).YourMainForm_Click(null, null);
}
return false;
}
}
Then in your main form add this to register the message filter:
GlobalMouseHandler globalClick = new GlobalMouseHandler();
Application.AddMessageFilter(globalClick);
And add this function to do whatever you have to, in your form:
public void YourMainForm_Click(object sender, EventArgs e)
{
// do anything here...
}
Solution 1
Subscribing to each and every event on every control within a form is certainly the most simplest approach to take, since you just use the code given by Ramesh.
However, another technique involves overriding the default windows message processing method ("WndProc") on the parent control - in this case, the form that contains all the controls.
This has a side effect that you won't be able to detect when the mouse cursor moves over controls contained inside another parent control.
For example, you won't be able to detect when the mouse cursor is over a TextBox that is contained inside a TabControl. This is because the TabControl will continue to process all mouse events.
Solution 2
The following solution will overcome all issues in attempting to detect which control the mouse cursor is over using a technique known as windows hooks.
Hooks essentially allow us to trap mouse and keyboard events even before they are dispatched to the window with focus.
Here's a sample:
public enum HookType : int
{
WH_JOURNALRECORD = 0,
WH_JOURNALPLAYBACK = 1,
WH_KEYBOARD = 2,
WH_GETMESSAGE = 3,
WH_CALLWNDPROC = 4,
WH_CBT = 5,
WH_SYSMSGFILTER = 6,
WH_MOUSE = 7,
WH_HARDWARE = 8,
WH_DEBUG = 9,
WH_SHELL = 10,
WH_FOREGROUNDIDLE = 11,
WH_CALLWNDPROCRET = 12,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int X;
public int Y;
}
[StructLayout(LayoutKind.Sequential)]
public struct MouseHookStruct
{
public POINT pt;
public int hwnd;
public int hitTestCode;
public int dwExtraInfo;
}
[DllImport("user32.dll", SetLastError = true)]
static extern int SetWindowsHookEx(HookType hook, HookProc callback, IntPtr hInstance, uint dwThreadId);
[DllImport("user32.dll", SetLastError= true)]
static extern int CallNextHookEx(int hook, int code, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
static extern int GetLastError();
[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId();
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
private static int hHook;
public Form1()
{
InitializeComponent();
hHook = SetWindowsHookEx(HookType.WH_MOUSE, MouseHookProc, IntPtr.Zero, (uint)GetCurrentThreadId());
if (hHook == 0)
MessageBox.Show("GetLastError: " + GetLastError());
}
private int MouseHookProc(int code, IntPtr wParam, IntPtr lParam)
{
//Marshall the data from the callback.
MouseHookStruct mouseInfo = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
if (code < 0)
{
return CallNextHookEx(hHook, code, wParam, lParam);
}
else
{
//Create a string variable that shows the current mouse coordinates.
String strCaption = "x = " + mouseInfo.pt.X.ToString("d") +
" y = " + mouseInfo.pt.Y.ToString("d");
//You must get the active form because it is a static function.
Form tempForm = Form.ActiveForm;
Control c = Control.FromHandle((IntPtr)mouseInfo.hwnd);
if (c != null)
label1.Text = c.Name;
else
label1.Text = "Control not found";
//Set the caption of the form.
tempForm.Text = strCaption;
return CallNextHookEx(hHook, code, wParam, lParam);
}
}
Other conttrols in the form cannot listen to the Mouse event handlers of the form. Because each control got its own mouse event listners.
But You can subscribe each controls mouse events to the forms mouse events
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MDown);
this.label1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MDown);
this.ListBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MDown);
this way you can have single handler for all the controls mouse events.

WPF Window Drag/Move Boundary

just curious if you know of any way to setup a drag boundary for a window?
It would be nice to have these properties:
Me.MinLeft = 10
Me.MinTop = 10
Me.MaxLeft = 150
Me.MaxTop = 150
Those are made up properties, btw, which would be nice to have.
I know I could probably setup a timer to fire ever 10th of a second and check the left and top and then move it back if it's over. But it would be more elegant to have the window act like it hit a wall and can't go any farther, like moving to the edge of the screen or something similar.
Edit: There seems to be some confusion somewhere, the point I'm trying to make is in the paragraph above, dragging, not re-sizing.
Here is teh "magic" you need to create this functionality, all you have to do is set the Window_SourceInitialized method to the window's SourceInitialized event and insert you logic where the big comment is.
I combined this code from several sources, so there could be some syntax errors in it.
internal enum WM
{
WINDOWPOSCHANGING = 0x0046,
}
[StructLayout(LayoutKind.Sequential)]
internal struct WINDOWPOS
{
public IntPtr hwnd;
public IntPtr hwndInsertAfter;
public int x;
public int y;
public int cx;
public int cy;
public int flags;
}
private void Window_SourceInitialized(object sender, EventArgs ea)
{
HwndSource hwndSource = (HwndSource)HwndSource.FromVisual((Window)sender);
hwndSource.AddHook(DragHook);
}
private static IntPtr DragHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handeled)
{
switch ((WM)msg)
{
case WM.WINDOWPOSCHANGING:
{
WINDOWPOS pos = (WINDOWPOS)Marshal.PtrToStructure(lParam, typeof(WINDOWPOS));
if ((pos.flags & (int)SWP.NOMOVE) != 0)
{
return IntPtr.Zero;
}
Window wnd = (Window)HwndSource.FromHwnd(hwnd).RootVisual;
if (wnd == null)
{
return IntPtr.Zero;
}
bool changedPos = false;
// ***********************
// Here you check the values inside the pos structure
// if you want to override tehm just change the pos
// structure and set changedPos to true
// ***********************
if (!changedPos)
{
return IntPtr.Zero;
}
Marshal.StructureToPtr(pos, lParam, true);
handeled = true;
}
break;
}
return IntPtr.Zero;
}
As I have no doubt that Nir's answer will work spending a little time implementing it, I was able to do what I wanted a little bit more elegant with this code:
Private Sub myWindow_LocationChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LocationChanged
Dim primaryBounds As System.Drawing.Rectangle = Windows.Forms.Screen.PrimaryScreen.Bounds
Dim windowBounds As System.Drawing.Rectangle = New System.Drawing.Rectangle(CInt(Me.Left), CInt(Me.Top), CInt(Me.Width), CInt(Me.Height))
If (windowBounds.Left < 0) Then
windowBounds = New System.Drawing.Rectangle(0, windowBounds.Top, windowBounds.Width, windowBounds.Height)
ElseIf (windowBounds.Right > primaryBounds.Right) Then
windowBounds = New System.Drawing.Rectangle(primaryBounds.Right - windowBounds.Width, windowBounds.Top, windowBounds.Width, windowBounds.Height)
End If
If (windowBounds.Top < 0) Then
windowBounds = New System.Drawing.Rectangle(windowBounds.Left, 0, windowBounds.Width, windowBounds.Height)
ElseIf (windowBounds.Bottom > primaryBounds.Bottom) Then
windowBounds = New System.Drawing.Rectangle(windowBounds.Left, primaryBounds.Bottom - windowBounds.Height, windowBounds.Width, windowBounds.Height)
End If
Me.Left = windowBounds.Left
Me.Top = windowBounds.Top
End Sub
This made the window being dragged stay within the primary screen (whole window), but you could easily change the bounds to whatever values you needed.
There are dependency properties for WPF's Window for this purpose.
Here they are:
Window.MaxWidth
Window.MaxHeight
These properties will constrain the size of the Window, just like the WinForm's Form.
Maybe you could handle PreviewMouseMove (either the event or override the corresponding protected method) and set e.Handled = true whenever the mouse movement would cause the window to move outside the region you want to constrain it to.
This seems like the most logical, WPF-like way of doing this.

How can I invoke the dialog to set printer options manually?

I'm using WPF and need to let users set some print related options like printer and printer properties (e.g. papertray, landscape/portrait, duplex, etc). I'm aware of the PrintDialog class to get a PrintQueue and PrintTicket object. However I need to create I custom solution and can not show the PrintDialog.
I manage to get the available PrintQueue objects and let users select a printer. I'm struggling with the printer properties.
My question is: how can I show the dialog in which a user can set the printer properties for the selected PrintQueue (the dialog that is shown when a user clicks on the Properties button in the WPF PrintDialog).
The following code was found here (minus the Window_Loaded event). I tested it and it seems to work like a charm. Obviously you'll have to set the printer name in the PrinterSettings object before displaying the dialog.
Hope this works for you:
[DllImport("kernel32.dll")]
static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("kernel32.dll")]
static extern bool GlobalUnlock(IntPtr hMem);
[DllImport("kernel32.dll")]
static extern bool GlobalFree(IntPtr hMem);
[DllImport("winspool.Drv", EntryPoint = "DocumentPropertiesW", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
static extern int DocumentProperties(IntPtr hwnd, IntPtr hPrinter, [MarshalAs(UnmanagedType.LPWStr)] string pDeviceName, IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);
private const Int32 DM_OUT_BUFFER = 14;
public void OpenPrinterPropertiesDialog(PrinterSettings printerSettings, System.IntPtr pHandle) {
IntPtr hDevMode = printerSettings.GetHdevmode();
IntPtr pDevMode = GlobalLock(hDevMode);
Int32 fMode = 0;
int sizeNeeded = DocumentProperties(pHandle, IntPtr.Zero, printerSettings.PrinterName, pDevMode, pDevMode, fMode);
IntPtr devModeData = Marshal.AllocHGlobal(sizeNeeded);
fMode = DM_OUT_BUFFER;
DocumentProperties(pHandle, IntPtr.Zero, printerSettings.PrinterName, devModeData, pDevMode, fMode);
GlobalUnlock(hDevMode);
printerSettings.SetHdevmode(devModeData);
printerSettings.DefaultPageSettings.SetHdevmode(devModeData);
GlobalFree(hDevMode);
Marshal.FreeHGlobal(devModeData);
}
private void Window_Loaded(object sender, RoutedEventArgs e) {
OpenPrinterPropertiesDialog(new PrinterSettings(), new WindowInteropHelper(this).Handle);
}
If you target x86 compilation and run from a x64 machine, the code from Pwninstein will not work: when allocating devModeData, DocumentPropreties will always fail and returns a sizeNeeded of -1, with a LastError code 13.
To solve the problem, either make sure you target AnyCPU or just change the call to DocumentPropreties to the following:
int sizeNeeded = DocumentProperties(pHandle,
IntPtr.Zero,
printerSettings.PrinterName,
IntPtr.Zero, // This solves it
pDevMode,
fMode);
Using IntPtr.Zero instead of a proper pointer to a DevMode structure looks wrong, but that first call to DocumentProperties does not attempt to modify the memory at that position. The only data returned by the call is the memory size needed to store the device mode data that represents the internal parameters of the print driver.
Reference:
PInvoke.Net page on DocumentProperties

Resources