using CFileDialog::AddCheckButton fails - windows

OK, I am trying to use CFileDialog::AddCheckButton. The function call succeeds and I'm able to see the new check box. I'm unable to see any events and while I can override OnInitDialog, overriding OnOK is ignored. I'm not sure what I'm doing wrong:
//header
class CTPSaveDialog : public CFileDialog
{
DECLARE_DYNAMIC(CTPSaveDialog)
static const CString CTPSaveDialog::m_cstrFilter;
public:
BOOL m_bForce;
CTPSaveDialog(
LPCTSTR lpszDefExt = NULL,
LPCTSTR lpszFileName = NULL,
DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
CWnd* pParentWnd = NULL,
DWORD dwSize = 0);
~CTPSaveDialog();
virtual BOOL OnInitDialog();
DECLARE_MESSAGE_MAP()
afx_msg void OnBnClickedCheckForce();
virtual void OnOK();
};
// implementation
const CString CTPSaveDialog::m_cstrFilter = "JPEG images (*.jpg)|*.jpg|TIFF Format (*.tif)|*.tif|Windows Bitmap (*.bmp)|*.bmp|Portable Network Graphics (*.png)|*.png|GIF (*.gif)|*.gif||";
IMPLEMENT_DYNAMIC(CTPSaveDialog, CFileDialog)
CTPSaveDialog::CTPSaveDialog(LPCTSTR lpszDefExt, LPCTSTR lpszFileName, DWORD dwFlags, CWnd * pParentWnd, DWORD dwSize) :
CFileDialog(FALSE, lpszDefExt, lpszFileName, dwFlags, m_cstrFilter, pParentWnd, dwSize, TRUE)
{
AddCheckButton(IDC_CHK_FORCE, "Force", FALSE);
m_bForce = FALSE;
m_ofn.lpstrTitle = "Write Simulation To File";
}
CTPSaveDialog::~CTPSaveDialog()
{
}
BOOL CTPSaveDialog::OnInitDialog()
{
CFileDialog::OnInitDialog();
if (GetDlgItem(IDC_CHK_FORCE))
SendDlgItemMessage(IDC_CHK_FORCE, BM_SETCHECK, m_bForce ? BST_CHECKED : BST_UNCHECKED);
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
BEGIN_MESSAGE_MAP(CTPSaveDialog, CFileDialog)
ON_BN_CLICKED(IDC_CHK_FORCE, &CTPSaveDialog::OnBnClickedCheckForce)
END_MESSAGE_MAP()
void CTPSaveDialog::CTPSaveDialog()
{
m_bForce = !m_bForce;
}
void CTPSaveDialog::OnOK()
{
// TODO: Add your specialized code here and/or call the base class
CFileDialog::OnOK();
}

In CFileDialog with Vista style, windows messages are not handled in message map. Instead CFileDialog uses specific virtual functions. You only need to declare and define these functions.
Use OnCheckButtonToggled to detect if check box is clicked.
Use OnFileNameOK to detect when file is selected and Open/Save button is clicked.
Use SetCheckButtonState to set/unset the check button (not SendDlgItemMessage)
See CFileDialog for all available methods.
As stated in documentation, OnInitDialog is not supported either:
Some CFileDialog methods are not supported under Windows Vista or
later. Check the individual method topic for information about whether
the method is supported. In addition, the following inherited
functions are not supported under Windows Vista or later:
CDialog::OnInitDialog
...
Just do the initialization in the constructor or before calling DoModal(), and override these functions:
class CTPSaveDialog : public CFileDialog
{
...
virtual void OnCheckButtonToggled(DWORD dwIDCtl, BOOL bChecked);
virtual BOOL OnFileNameOK();
};
void CTPSaveDialog::OnCheckButtonToggled(DWORD dwIDCtl, BOOL bChecked)
{
if (dwIDCtl == IDC_CHK_FORCE)
TRACE("Is checked? %d\n", bChecked);
}
BOOL CTPSaveDialog::OnFileNameOK()
{
TRACE("Clicked Open/Save button\n");
//return FALSE to close the dialog
return FALSE;
}

Related

Reliably determine PID of a process that updated clipboard [duplicate]

I am creating a clipboard manager in C# and from time to time I experience that the clipboard is being set empty by some application.
This happens in e.g. Excel when deselecting what is just copied, so I need to figure out if the clipboard is empty but how can I get the application name that updates the clipboard?
I hope that I somehow can get the HWnd handle of the application that updates the clipboard so I can then lookup the process behind it with this code:
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
...
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_CLIPBOARDUPDATE:
// How to get the "handle" HWnd?
IntPtr handle = ??? <============= HOW TO GET THIS ONE ???
// Get the process ID from the HWnd
uint processId = 0;
GetWindowThreadProcessId(handle, out processId);
// Get the process name from the process ID
string processName = Process.GetProcessById((int)processId).ProcessName;
Console.WriteLine("Clipboard UPDATE event from [" + processName + "]");
break;
}
default:
base.WndProc(ref m);
break;
}
}
I would have hoped that I could use the HWnd from the Message object, but this seems to be my own application - probably to notify the application with this process ID:
If I can get it any other way then this would of course be fully okay also but I would appreciate any insights on this :-)
Solution
Based on #Jimi's answer then this is very simple. I can just add the below 3 lines to my original code:
// Import the "GetClipboardOwner" function from the User32 library
[DllImport("user32.dll")]
public static extern IntPtr GetClipboardOwner();
...
// Replace the original line with "HOW TO GET THIS ONE" with this line below - this will give the HWnd handle for the application that has changed the clipboard:
IntPtr handle = GetClipboardOwner();
You can call GetClipboardOwner() to get the handle of the Window that last set or cleared the Clipboard (the operation that triggered the notification).
[...] In general, the clipboard owner is the window that last placed data in the Clipboard.
The EmptyClipboard function assigns Clipboard ownership.
There are special cases when a Process passes a null handle to OpenClipboard(): read the Remarks section of this function and the EmptyClipboard function.
Before calling EmptyClipboard, an application must open the Clipboard
by using the OpenClipboard function. If the application specifies a
NULL window handle when opening the clipboard, EmptyClipboard succeeds
but sets the clipboard owner to NULL. Note that this causes
SetClipboardData to fail.
▶ Here I'm using a NativeWindow derived class to setup a Clipboard listener. The Window that process the Clipboard update messages is created initializing a CreateParams object and passing this parameter to the NativeWindow.CreateHandle(CreateParams) method, to create an invisible Window.
Then override WndProc of the initialized NativeWindow, to receive WM_CLIPBOARDUPDATE notifications.
The AddClipboardFormatListener function is used to place the Window in the system Clipboard listeners chain.
▶ The ClipboardUpdateMonitor class generates an event when a Clipboard notification is received. The custom ClipboardChangedEventArgs object passed in the event contains the Handle of the Clipboard Owner, as returned by GetClipboardOwner(), the ThreadId and ProcessId returned by GetWindowThreadProcessId() and the Process name, identified by Process.GetProcessById().
You can setup a ClipboardUpdateMonitor object like this:
This class can also be initialized in Program.cs
private ClipboardUpdateMonitor clipboardMonitor = null;
// [...]
clipboardMonitor = new ClipboardUpdateMonitor();
clipboardMonitor.ClipboardChangedNotify += this.ClipboardChanged;
// [...]
private void ClipboardChanged(object sender, ClipboardChangedEventArgs e)
{
Console.WriteLine(e.ProcessId);
Console.WriteLine(e.ProcessName);
Console.WriteLine(e.ThreadId);
}
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Windows.Forms;
public sealed class ClipboardUpdateMonitor : IDisposable
{
private bool isDisposed = false;
private static ClipboardWindow window = null;
public event EventHandler<ClipboardChangedEventArgs> ClipboardChangedNotify;
public ClipboardUpdateMonitor()
{
window = new ClipboardWindow();
if (!NativeMethods.AddClipboardFormatListener(window.Handle)) {
throw new TypeInitializationException(nameof(ClipboardWindow),
new Exception("ClipboardFormatListener could not be initialized"));
}
window.ClipboardChanged += ClipboardChangedEvent;
}
private void ClipboardChangedEvent(object sender, ClipboardChangedEventArgs e)
=> ClipboardChangedNotify?.Invoke(this, e);
public void Dispose()
{
if (!isDisposed) {
// Cannot allow to throw exceptions here: add more checks to verify that
// the NativeWindow still exists and its handle is a valid handle
NativeMethods.RemoveClipboardFormatListener(window.Handle);
window?.DestroyHandle();
isDisposed = true;
}
}
~ClipboardUpdateMonitor() => Dispose();
private class ClipboardWindow : NativeWindow
{
public event EventHandler<ClipboardChangedEventArgs> ClipboardChanged;
public ClipboardWindow() {
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
var cp = new CreateParams();
cp.Caption = "ClipboardWindow";
cp.Height = 100;
cp.Width = 100;
cp.Parent = IntPtr.Zero;
cp.Style = NativeMethods.WS_CLIPCHILDREN;
cp.ExStyle = NativeMethods.WS_EX_CONTROLPARENT | NativeMethods.WS_EX_TOOLWINDOW;
this.CreateHandle(cp);
}
protected override void WndProc(ref Message m)
{
switch (m.Msg) {
case NativeMethods.WM_CLIPBOARDUPDATE:
IntPtr owner = NativeMethods.GetClipboardOwner();
var threadId = NativeMethods.GetWindowThreadProcessId(owner, out uint processId);
string processName = string.Empty;
if (processId != 0) {
using (var proc = Process.GetProcessById((int)processId)) {
processName = proc?.ProcessName;
}
}
ClipboardChanged?.Invoke(null, new ClipboardChangedEventArgs(processId, processName, threadId));
m.Result = IntPtr.Zero;
break;
default:
base.WndProc(ref m);
break;
}
}
}
}
Custom EventArgs object used to carry the information collected about the Clipboard Owner:
public class ClipboardChangedEventArgs : EventArgs
{
public ClipboardChangedEventArgs(uint processId, string processName, uint threadId)
{
this.ProcessId = processId;
this.ProcessName = processName;
this.ThreadId = threadId;
}
public uint ProcessId { get; }
public string ProcessName { get; }
public uint ThreadId { get; }
}
NativeMethods class:
internal static class NativeMethods
{
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool AddClipboardFormatListener(IntPtr hwnd);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool RemoveClipboardFormatListener(IntPtr hwnd);
[DllImport("user32.dll")]
internal static extern IntPtr GetClipboardOwner();
[DllImport("user32.dll", SetLastError = true)]
internal static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
internal const int WM_CLIPBOARDUPDATE = 0x031D;
internal const int WS_CLIPCHILDREN = 0x02000000;
internal const int WS_EX_TOOLWINDOW = 0x00000080;
internal const int WS_EX_CONTROLPARENT = 0x00010000;
}

MFC: how to fix redraw properly for inherited CDialogBar?

I make an inherited class from CDialogBar.
class CMyDialogBar : public CDialogBar
{
DECLARE_DYNAMIC(CMyDialogBar)
// Implementation
public:
BOOL Create(CWnd * pParentWnd, UINT nIDTemplate, UINT nStyle, UINT nID);
BOOL Create(CWnd * pParentWnd, LPCTSTR lpszTemplateName, UINT nStyle, UINT nID);
protected:
virtual void DoDataExchange(CDataExchange* pDX) { return CDialogBar::DoDataExchange(pDX); }
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
DECLARE_MESSAGE_MAP()
};
The only big change is the function OnEraseBkgnd() because I like the background to be white.
BOOL CMyDialogBar::OnEraseBkgnd(CDC* pDC)
{
return TRUE;
}
It works OK. However, when I move the rebar around it doesn't redraw correctly as shown in the figure below.
The source code can be downloaded here: https://138.197.210.223/test/My.zip.
You need your OnEraseBkgnd override to actually erase the background! For example, to set the entire client rectangle to white, you could do this:
BOOL CMyDialogBar::OnEraseBkgnd(CDC *pDC)
{
RECT wr; GetClientRect(&wr);
pDC->FillSolidRect(&wr, RGB(255,255,255));
return TRUE;
}
EDIT: Maybe you already have this, but also be sure to add ON_WM_ERASEBKGND to your message map:
BEGIN_MESSAGE_MAP(CMyDialogBar, CDialogBar)
// ... (other message handlers, if any) ...
ON_WM_ERASEBKGND()
END_MESSAGE_MAP()

Show touch keyboard (TabTip.exe) in Windows 10 Anniversary edition

In Windows 8 and Windows 10 before Anniversary update it was possible to show touch keyboard by starting
C:\Program Files\Common Files\microsoft shared\ink\TabTip.exe
It no longer works in Windows 10 Anniversary update; the TabTip.exe process is running, but the keyboard is not shown.
Is there a way to show it programmatically?
UPDATE
I found a workaround - fake mouse click on touch keyboard icon in system tray. Here is code in Delphi
// Find tray icon window
function FindTrayButtonWindow: THandle;
var
ShellTrayWnd: THandle;
TrayNotifyWnd: THandle;
begin
Result := 0;
ShellTrayWnd := FindWindow('Shell_TrayWnd', nil);
if ShellTrayWnd > 0 then
begin
TrayNotifyWnd := FindWindowEx(ShellTrayWnd, 0, 'TrayNotifyWnd', nil);
if TrayNotifyWnd > 0 then
begin
Result := FindWindowEx(TrayNotifyWnd, 0, 'TIPBand', nil);
end;
end;
end;
// Post mouse click messages to it
TrayButtonWindow := FindTrayButtonWindow;
if TrayButtonWindow > 0 then
begin
PostMessage(TrayButtonWindow, WM_LBUTTONDOWN, MK_LBUTTON, $00010001);
PostMessage(TrayButtonWindow, WM_LBUTTONUP, 0, $00010001);
end;
UPDATE 2
Another thing I found is that setting this registry key restores old functionality when starting TabTip.exe shows touch keyboard
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\TabletTip\1.7\EnableDesktopModeAutoInvoke=1
OK, I reverse engineered what explorer does when the user presses that button in the system tray.
Basically it creates an instance of an undocumented interface ITipInvocation and calls its Toggle(HWND) method, passing desktop window as an argument. As the name suggests, the method either shows or hides the keyboard depending on its current state.
Please note that explorer creates an instance of ITipInvocation on every button click. So I believe the instance should not be cached. I also noticed that explorer never calls Release() on the obtained instance. I'm not too familiar with COM, but this looks like a bug.
I tested this in Windows 8.1, Windows 10 & Windows 10 Anniversary Edition and it works perfectly. Here's a minimal example in C that obviously lacks some error checks.
#include <initguid.h>
#include <Objbase.h>
#pragma hdrstop
// 4ce576fa-83dc-4F88-951c-9d0782b4e376
DEFINE_GUID(CLSID_UIHostNoLaunch,
0x4CE576FA, 0x83DC, 0x4f88, 0x95, 0x1C, 0x9D, 0x07, 0x82, 0xB4, 0xE3, 0x76);
// 37c994e7_432b_4834_a2f7_dce1f13b834b
DEFINE_GUID(IID_ITipInvocation,
0x37c994e7, 0x432b, 0x4834, 0xa2, 0xf7, 0xdc, 0xe1, 0xf1, 0x3b, 0x83, 0x4b);
struct ITipInvocation : IUnknown
{
virtual HRESULT STDMETHODCALLTYPE Toggle(HWND wnd) = 0;
};
int WinMain(HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
HRESULT hr;
hr = CoInitialize(0);
ITipInvocation* tip;
hr = CoCreateInstance(CLSID_UIHostNoLaunch, 0, CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER, IID_ITipInvocation, (void**)&tip);
tip->Toggle(GetDesktopWindow());
tip->Release();
return 0;
}
Here's the C# version as well:
class Program
{
static void Main(string[] args)
{
var uiHostNoLaunch = new UIHostNoLaunch();
var tipInvocation = (ITipInvocation)uiHostNoLaunch;
tipInvocation.Toggle(GetDesktopWindow());
Marshal.ReleaseComObject(uiHostNoLaunch);
}
[ComImport, Guid("4ce576fa-83dc-4F88-951c-9d0782b4e376")]
class UIHostNoLaunch
{
}
[ComImport, Guid("37c994e7-432b-4834-a2f7-dce1f13b834b")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface ITipInvocation
{
void Toggle(IntPtr hwnd);
}
[DllImport("user32.dll", SetLastError = false)]
static extern IntPtr GetDesktopWindow();
}
Update: per #EugeneK comments, I believe that tabtip.exe is the COM server for the COM component in question, so if your code gets REGDB_E_CLASSNOTREG, it should probably run tabtip.exe and try again.
I had the same problem too. It took me much time and headache, but Thanks to Alexei and Torvin I finally got it working on Win 10 1709. Visibility check was the difficulty. Maybe The OSKlib Nuget could be updated. Let me sum up the complete sulotion (For sure my code has some unnecessary lines now):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;
using Osklib.Interop;
using System.Runtime.InteropServices;
using System.Threading;
namespace OSK
{
public static class OnScreenKeyboard
{
static OnScreenKeyboard()
{
var version = Environment.OSVersion.Version;
switch (version.Major)
{
case 6:
switch (version.Minor)
{
case 2:
// Windows 10 (ok)
break;
}
break;
default:
break;
}
}
private static void StartTabTip()
{
var p = Process.Start(#"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe");
int handle = 0;
while ((handle = NativeMethods.FindWindow("IPTIP_Main_Window", "")) <= 0)
{
Thread.Sleep(100);
}
}
public static void ToggleVisibility()
{
var type = Type.GetTypeFromCLSID(Guid.Parse("4ce576fa-83dc-4F88-951c-9d0782b4e376"));
var instance = (ITipInvocation)Activator.CreateInstance(type);
instance.Toggle(NativeMethods.GetDesktopWindow());
Marshal.ReleaseComObject(instance);
}
public static void Show()
{
int handle = NativeMethods.FindWindow("IPTIP_Main_Window", "");
if (handle <= 0) // nothing found
{
StartTabTip();
Thread.Sleep(100);
}
// on some devices starting TabTip don't show keyboard, on some does ¯\_(ツ)_/¯
if (!IsOpen())
{
ToggleVisibility();
}
}
public static void Hide()
{
if (IsOpen())
{
ToggleVisibility();
}
}
public static bool Close()
{
// find it
int handle = NativeMethods.FindWindow("IPTIP_Main_Window", "");
bool active = handle > 0;
if (active)
{
// don't check style - just close
NativeMethods.SendMessage(handle, NativeMethods.WM_SYSCOMMAND, NativeMethods.SC_CLOSE, 0);
}
return active;
}
public static bool IsOpen()
{
return GetIsOpen1709() ?? GetIsOpenLegacy();
}
[DllImport("user32.dll", SetLastError = false)]
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title = null);
[DllImport("user32.dll", SetLastError = false)]
private static extern uint GetWindowLong(IntPtr wnd, int index);
private static bool? GetIsOpen1709()
{
// if there is a top-level window - the keyboard is closed
var wnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, WindowClass1709, WindowCaption1709);
if (wnd != IntPtr.Zero)
return false;
var parent = IntPtr.Zero;
for (;;)
{
parent = FindWindowEx(IntPtr.Zero, parent, WindowParentClass1709);
if (parent == IntPtr.Zero)
return null; // no more windows, keyboard state is unknown
// if it's a child of a WindowParentClass1709 window - the keyboard is open
wnd = FindWindowEx(parent, IntPtr.Zero, WindowClass1709, WindowCaption1709);
if (wnd != IntPtr.Zero)
return true;
}
}
private static bool GetIsOpenLegacy()
{
var wnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, WindowClass);
if (wnd == IntPtr.Zero)
return false;
var style = GetWindowStyle(wnd);
return style.HasFlag(WindowStyle.Visible)
&& !style.HasFlag(WindowStyle.Disabled);
}
private const string WindowClass = "IPTip_Main_Window";
private const string WindowParentClass1709 = "ApplicationFrameWindow";
private const string WindowClass1709 = "Windows.UI.Core.CoreWindow";
private const string WindowCaption1709 = "Microsoft Text Input Application";
private enum WindowStyle : uint
{
Disabled = 0x08000000,
Visible = 0x10000000,
}
private static WindowStyle GetWindowStyle(IntPtr wnd)
{
return (WindowStyle)GetWindowLong(wnd, -16);
}
}
[ComImport]
[Guid("37c994e7-432b-4834-a2f7-dce1f13b834b")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface ITipInvocation
{
void Toggle(IntPtr hwnd);
}
internal static class NativeMethods
{
[DllImport("user32.dll", EntryPoint = "FindWindow")]
internal static extern int FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "SendMessage")]
internal static extern int SendMessage(int hWnd, uint Msg, int wParam, int lParam);
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow", SetLastError = false)]
internal static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll", EntryPoint = "GetWindowLong")]
internal static extern int GetWindowLong(int hWnd, int nIndex);
internal const int GWL_STYLE = -16;
internal const int GWL_EXSTYLE = -20;
internal const int WM_SYSCOMMAND = 0x0112;
internal const int SC_CLOSE = 0xF060;
internal const int WS_DISABLED = 0x08000000;
internal const int WS_VISIBLE = 0x10000000;
}
}
The only solution I've found to work is by sending PostMessage as you've mentioned in answer 1. Here's the C# version of it in case someone needs it.
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string sClassName, string sAppName);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string lclassName, string windowTitle);
[DllImport("User32.Dll", EntryPoint = "PostMessageA")]
static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
var trayWnd = FindWindow("Shell_TrayWnd", null);
var nullIntPtr = new IntPtr(0);
if (trayWnd != nullIntPtr)
{
var trayNotifyWnd = FindWindowEx(trayWnd, nullIntPtr, "TrayNotifyWnd", null);
if (trayNotifyWnd != nullIntPtr)
{
var tIPBandWnd = FindWindowEx(trayNotifyWnd, nullIntPtr, "TIPBand", null);
if (tIPBandWnd != nullIntPtr)
{
PostMessage(tIPBandWnd, (UInt32)WMessages.WM_LBUTTONDOWN, 1, 65537);
PostMessage(tIPBandWnd, (UInt32)WMessages.WM_LBUTTONUP, 1, 65537);
}
}
}
public enum WMessages : int
{
WM_LBUTTONDOWN = 0x201,
WM_LBUTTONUP = 0x202,
WM_KEYDOWN = 0x100,
WM_KEYUP = 0x101,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14,
}
I detect 4 situations when trying to open Touch Keyboard on Windows 10 Anniversary Update
Keyboard is Visible - when "IPTIP_Main_Window" is present, NOT disabled and IS visible
Keyboard is not visible - when "IPTIP_Main_Window" is present but disabled
Keyboard is not visible - when "IPTIP_Main_Window" is present but NOT disabled and NOT visible
Keyboard is not visible - when "IPTIP_Main_Window" is NOT present
1 - nothing to do
2+3 - activating via COM
4 - most interesting scenario. In some devices starting TabTip process opens touch keyboard, on some - not. So we must start TabTip process, wait for appearing window "IPTIP_Main_Window", check it for visibility and activate it via COM if nessesary.
I make small library for my project, you can use it - osklib
The following code will always work since it uses latest MS Api
I put it into a dll (Needed for a Delphi project) but it is a plain C
Also useful for obtaining the keyboard size and adjusting application layout
//*******************************************************************
//
// RETURNS KEYBOARD RECTANGLE OR EMPTY ONE IF KEYBOARD IS NOT VISIBLE
//
//*******************************************************************
RECT __stdcall GetKeyboardRect()
{
IFrameworkInputPane *inputPane = NULL;
RECT prcInputPaneScreenLocation = { 0,0,0,0 };
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if (SUCCEEDED(hr))
{
hr = CoCreateInstance(CLSID_FrameworkInputPane, NULL, CLSCTX_INPROC_SERVER, IID_IFrameworkInputPane, (LPVOID*)&inputPane);
if (SUCCEEDED(hr))
{
hr=inputPane->Location(&prcInputPaneScreenLocation);
if (!SUCCEEDED(hr))
{
}
inputPane->Release();
}
}
CoUninitialize();
return prcInputPaneScreenLocation;
}
There is still some mystery about how the touch keyboard is set visible by Windows 10 Anniversary Update. I'm actually having the exact same issue and here are the lastest infos i've found :
Windows 10 1607 works in two modes : Desktop and Tablet. While in Desktop mode, TabTip.exe can be called but won't show. While in Tablet mode, everything works fine : TabTip.exe shows itself when called. So a 100% working workaround is to set your computer in Tablet Mode but who wants his desktop/laptop to work in tablet mode ? Not me anyway !
You can use the "EnableDesktopModeAutoInvoke" Key (HKCU, DWORD set to 1) and on some computers running 1607 it worked great while in Desktop Mode. But for some unknown reasons, it is not working on my HP touchpad.
Please note that this registry value is the "Show touch keyboard on desktop mode if there is no attached keyboard" option in Windows parameters > touch
You can use Torvin's code to show TabTip.exe (as mentioned TabTip.exe should be running when you do the COM stuff), it is working fine on some computers running 1607 (including my HP touchpad ! yay !) But it will do nothing on some others comps with the same windows Build.
So far tested on 4 different computers and i'm unable to get something working fine on all...
The problem seems to be with setting of Windows OS. I have faced same issue with the app I was developing. With Windows 8 and 10 (before update) code that called keyboard worked fine, but after update failed to work. After reading this article, I did following:
Pressed Win+I to open the Settings app
Clicked on Devices > Typing
Turned "Automatically show the touch keyboard in windowed apps when there’s no keyboard attached to your device" ON.
Right after that keyboard starting showing up in Windows 10 also.
Implementing the IValueProvider/ITextProvider in your control is a correct way to achieve this, as described here: https://stackoverflow.com/a/43886052/1184950
I tried multiple things that did not work. But I discovered that I can use the Shortcut Keys Windows/Ctrl/O to open the On Screen Key Board.
Also there is a Nuget package: Input Simulator by Michael Noonan.
If you install the InputSimulator NuGet package in your Winforms project - then add code like this to an event, like a button:
private void button1_Click(object sender, EventArgs e)
{
var simu = new InputSimulator();
simu.Keyboard.ModifiedKeyStroke(new[] { VirtualKeyCode.LWIN, VirtualKeyCode.CONTROL }, VirtualKeyCode.VK_O);
}
You will also need to add these using statements:
using WindowsInput;
using WindowsInput.Native;
Run your app and the button will display the keyboard and also hit it again and it will remove it.
I am on Windows 10 and vs 2019.
Set oShell = CreateObject("WScript.Shell")
oShell.AppActivate "Program Manager"
oShell.Run "tabtip.exe", 0, true
oShell.SendKeys "%{TAB}"
[HKEY_CURRENT_USER\SOFTWARE\Microsoft\TabletTip\1.7]
"EnableDesktopModeAutoInvoke"=dword:00000001
Following code works well on 21h1 version tablet and notebook,thanks for #torvin method
#include <dwmapi.h>
#include <windows.h>
#pragma comment(lib,"dwmapi.lib")
void toggleKeyboardShowState()
{
if(FindWindowEx(nullptr,nullptr,L"IPTip_Main_Window",nullptr)!=nullptr)
{
ITipInvocation *tip_invocation_;
if(CoCreateInstance(CLSID_UIHostNoLaunch,nullptr,CLSCTX_INPROC_HANDLER|CLSCTX_LOCAL_SERVER,IID_ITipInvocation,(void **)&tip_invocation_)==S_OK)
tip_invocation_->Toggle(GetDesktopWindow());
return;
}
PVOID OldValue=nullptr;
BOOL bRet=Wow64DisableWow64FsRedirection(&OldValue);
ShellExecute(nullptr,L"open",L"C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe",nullptr,nullptr,SW_SHOWNORMAL);
if(bRet)
Wow64RevertWow64FsRedirection(OldValue);
}
bool keyboardIsShow()
{
int cloaked=0;
return DwmGetWindowAttribute(FindWindowExW(FindWindowExW(nullptr,nullptr,L"ApplicationFrameWindow",nullptr),nullptr,L"Windows.UI.Core.CoreWindow",L"Microsoft Text Input Application"),DWMWA_CLOAKED,&cloaked,DWM_CLOAKED_INHERITED)==S_OK?0==cloaked:false;
}
It will start and show taptip and show it default if there it isn't in background when call toggleKeyboardShowState(),otherwise change taptip show state.
start tabtip process or hide->show
if(!keyboardIsShow())
toggleKeyboardShowState();
show->hide
if(keyboardIsShow())
toggleKeyboardShowState();
The keyboard show state can be switched even without if judgment.
Use this method:
Create osk.bat file and save it under your program folder ie. C:\My Software\osk.bat
Type in this osk.bat the following cmd:
"C:\Program Files\Common Files\Microsoft Shared\Ink\Tabtip.exe"
Use Windows Script to run this bat file
oWSH = CREATEOBJECT("wscript.shell")
oWSH.Run("osk.bat", 0, .T.)
In Win10 Ver 1803, DesktopMode, there is no reliable way to
toggle the "Touch Keyboard" on|off [ ITipInvocation.Toggle() ];
nor can you reliably discover if it's "up" ( on screen )
[ IFrameworkInputPane.Location() ]; both routines fail randomly.
Instead, ensure that "TabTIP.EXE" and "....InputApp.EXE"
only run when the keyboard is "up" ( on screen ).
To toggle the keyboard on and off ( from X.CPP in Jeff-Relf.Me/X.ZIP ):
if ( WM == WM_HOTKEY && C == 'K' ) {
// A mouse button takes me here. Jeff-Relf.Me/g600.PNG
if ( KillProc = 1, Running( L"TabTIP.EXE" ), KillProc = 1, Running(
L"WindowsInternal.ComposableShell.Experiences.TextInput.InputApp.EXE"
) )
// The keyboard was _On_ ( i.e. its processes were running ),
// so it was "turned _Off_" (killed); and we're done.
goto Done ;
// The keyboard was _Off_ ( i.e. no running processes ).
// Turn it _On_:
Launch( L"%CommonProgramFiles%/microsoft shared/ink/TabTIP.EXE" );
Sleep(99);
static const GUID CLSID_UIHostNoLaunch = { 0x4CE576FA, 0x83DC,
0x4f88, 0x95, 0x1C, 0x9D, 0x07, 0x82, 0xB4, 0xE3, 0x76 };
static const GUID IID_ITipInvocation = { 0x37c994e7, 0x432b,
0x4834, 0xa2, 0xf7, 0xdc, 0xe1, 0xf1, 0x3b, 0x83, 0x4b };
static struct ITipInvocation : IUnknown { virtual HRESULT
STDMETHODCALLTYPE Toggle( HWND wnd ) = 0 ; } * Tog ;
Tog = 0, CoCreateInstance( CLSID_UIHostNoLaunch, 0, CLSCTX_INPROC_HANDLER
| CLSCTX_LOCAL_SERVER, IID_ITipInvocation, (void**) & Tog );
// Firefox and Chrome need this:
Tog ? Tog->Toggle( GetDesktopWindow() ), Tog->Release() : 0 ; }
- - - - - - - - - - - - -
// To get the process list, and kill stuff:
#include <tlhelp32.H>
int KillProc ;
int Running( wchar * EXE ) { int Found ; HANDLE PIDs, aProc ;
PROCESSENTRY32 aPID = { sizeof aPID };
PIDs = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
Process32First( PIDs, &aPID );
while ( Found = !strCmpI( aPID.szExeFile, EXE ),
KillProc && Found && (
aProc = OpenProcess( PROCESS_TERMINATE, 0, aPID.th32ProcessID ),
aProc ? TerminateProcess( aProc, 9 ), CloseHandle( aProc ) : 0 ),
!Found && Process32Next( PIDs, &aPID ) );
KillProc = 0, CloseHandle( PIDs ); return Found ; }
Launch( wchar * Cmd ) { wchar _Cmd[333]; static PROCESS_INFORMATION Stat ;
static STARTUPINFO SU = { sizeof SU };
SetEnvironmentVariable( L"__compat_layer", L"RunAsInvoker" );
ExpandEnvironmentStrings( Cmd, _Cmd, 333 ), Cmd = _Cmd ;
if ( CreateProcess( 0, Cmd, 0,0,1,0,0,0, &SU , &Stat ) )
CloseHandle( Stat.hProcess ), CloseHandle( Stat.hThread ); }
// CoInitialize(0);

Creating MFC dialog to let the user choose file path

As title says, I am trying to create MFC dialog-based app to let the user select the file destination folder.
I am doing this by using CMFCShellTreeCtrl. However, somehow there is only one root item which is Desktop. I would like to see all items like My Computer, C drive etc.
Could you please tell me what's wrong and how do I fix it. Thanks.
Edit: Sorry I forgot to post my code. (Very simple dialog for browsing)
// BrowseDlg.cpp : implementation file
//
#include "stdafx.h"
#include "MFC Grab to FTP.h"
#include "BrowseDlg.h"
#include "afxdialogex.h"
// CBrowseDlg dialog
IMPLEMENT_DYNAMIC(CBrowseDlg, CDialog)
CBrowseDlg::CBrowseDlg(CWnd* pParent /*=NULL*/)
: CDialog(CBrowseDlg::IDD, pParent)
{
}
CBrowseDlg::~CBrowseDlg()
{
}
void CBrowseDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_PATH, m_PathTree);
}
BEGIN_MESSAGE_MAP(CBrowseDlg, CDialog)
ON_NOTIFY(TVN_SELCHANGED, IDC_PATH, &CBrowseDlg::OnTvnSelchangedMfcshelltree1)
ON_BN_CLICKED(IDOK, &CBrowseDlg::OnBnClickedOk)
END_MESSAGE_MAP()
// CBrowseDlg message handlers
BOOL CBrowseDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
m_PathTree.Expand(m_PathTree.GetRootItem(),TVE_EXPAND);
return TRUE; // return TRUE unless you set the focus to a control
}
void CBrowseDlg::OnTvnSelchangedMfcshelltree1(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR);
// TODO: Add your control notification handler code here
*pResult = 0;
}
void CBrowseDlg::OnBnClickedOk()
{
m_PathTree.GetItemPath(path,m_PathTree.GetSelectedItem());
// TODO: Add your control notification handler code here
CDialog::OnOK();
}
//
#pragma once
#include "afxshelltreectrl.h"
// CBrowseDlg dialog
// header file
class CBrowseDlg : public CDialog
{
DECLARE_DYNAMIC(CBrowseDlg)
public:
CBrowseDlg(CWnd* pParent = NULL); // standard constructor
virtual ~CBrowseDlg();
// Dialog Data
enum { IDD = IDD_BROWSER };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnTvnSelchangedMfcshelltree1(NMHDR *pNMHDR, LRESULT *pResult);
CString path;
CMFCShellTreeCtrl m_PathTree;
afx_msg void OnBnClickedOk();
virtual BOOL OnInitDialog();
};
The problem is that CShellManager in not initialized. You have to do it manually. To initialize it you need to call CWinAppEx::InitShellManager() in OnInitInstance() of your CWinApp-derived class.
There is an alternative to using CMFCShellTreeCtrl, if you just want to pick a folder: IFileDialog.
This is my code for a select folder dialog (rather complicated, because I still want to support Windows XP using XFolderDialog):
HINSTANCE hEasyCTXP_DLL = NULL;
// Select Folder Dialog -- uses either CXFolderDialog or IFileDialog
// to open a folder picker dialog depending on OS version
// returns "" if Cancel was pressed or something else went wrong
// Note: This is just multi-byte code and not yet unicode compatible!
BOOL SelectFolder(LPSTR sFolder, LPCTSTR sTitle = "Choose Folder")
{
OSVERSIONINFOEX osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(osvi);
if (GetVersionEx((OSVERSIONINFO *)&osvi) && osvi.dwMajorVersion >= 6) // Vista or higher?
{
if (!(hEasyCTXP_DLL = LoadLibrary("XPHelper.dll")))
{
AfxMessageBox("Error opening Select Folder dialog. XPHelper.dll may not be installed properly.");
return FALSE;
}
else
{
BOOL (__cdecl *pSelectFolder)(LPSTR, LPCTSTR);
pSelectFolder = (BOOL (__cdecl *)(LPSTR, LPCTSTR))GetProcAddress(hEasyCTXP_DLL, "SelectFolder");
if (pSelectFolder)
{
return (*pSelectFolder)(sFolder, sTitle);
}
else
{
AfxMessageBox("Error opening Select Folder dialog. (SelectFolder() function entry point not found.)");
return FALSE;
}
}
}
else // XP
{
CXFolderDialog dlg(sFolder);
dlg.SetTitle(sTitle);
if (dlg.DoModal() == IDOK)
{
CString csPath = dlg.GetPath();
strcpy(sFolder, (LPCTSTR)csPath);
return TRUE;
}
else
return FALSE;
}
}
Here comes the function I provide in XPHelper.dll. This dll is delay loaded only, if Vista or later OS is used, so the main program won't fail because of missing dependencies in Windows XP:
// sFolder should be at least MAX_FILE in size!
extern "C" BOOL SelectFolder(LPSTR sFolder, LPCTSTR sTitle)
{
BOOL bRet = TRUE;
IFileDialog *pfd;
LPWSTR pwstrPath;
HRESULT hr;
if (SUCCEEDED(hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd))))
{
DWORD dwOptions;
hr = pfd->GetOptions(&dwOptions);
if (SUCCEEDED(hr))
hr = pfd->SetOptions(dwOptions | FOS_PICKFOLDERS); // put IFileDialog in folder mode
if (SUCCEEDED(hr))
{
WCHAR wcTitle[MAX_PATH+1];
if (MultiByteToWideChar(CP_ACP, 0, sTitle, (int)min(strlen(sTitle), MAX_PATH), wcTitle, sizeof(MAX_PATH + 1)))
{
wcTitle[min(strlen(sTitle), MAX_PATH)] = '\0';
pfd->SetTitle(wcTitle); // Set dialog title
}
char *cp = sFolder;
WCHAR wcDefaultPath[MAX_PATH+1];
IShellItem *psi;
if (MultiByteToWideChar(CP_ACP, 0, cp, (int)strlen(cp), wcDefaultPath, MAX_PATH + 1))
{
wcDefaultPath[strlen(cp)] = '\0';
if (SUCCEEDED(::SHCreateItemFromParsingName(wcDefaultPath, NULL, IID_PPV_ARGS(&psi))))
{
hr = pfd->SetFileName(wcDefaultPath);
hr = pfd->SetFolder(psi);
psi->Release();
}
}
}
if (SUCCEEDED(hr))
hr = pfd->Show(AfxGetMainWnd()->GetSafeHwnd());
if (SUCCEEDED(hr))
{
IShellItem *psi;
if (SUCCEEDED(pfd->GetResult(&psi)))
{
if(SUCCEEDED(psi->GetDisplayName(SIGDN_FILESYSPATH, &pwstrPath)))
{
int nSize = (int)wcslen(pwstrPath);
WideCharToMultiByte(CP_ACP, 0, pwstrPath, nSize, sFolder, MAX_PATH+1, NULL, NULL);
sFolder[nSize] = '\0';
::CoTaskMemFree(pwstrPath);
}
else
{
AfxMessageBox("IShellItem::GetDisplayName() failed.");
bRet = FALSE;
}
psi->Release();
}
else
{
AfxMessageBox("IFileDialog failed.");
bRet = FALSE;
}
}
pfd->Release();
}
if(!SUCCEEDED(hr))
bRet = FALSE;
return bRet;
}

dll to caller main dialog

I am desparately in search of MFC dll sample that updates an edit field on a dialog derived from CDialog with a string using only the callback function. I realize static functions are the ones that are used in the calback.
I guess you realise that the dll should have something (like a separate thread, or a certain third-party message handler for this model. So, this is out of scope for this question.
Back to the question:
In order to create a callback function you need to "typedef" its prototype and pass the address of this function from your calling app to the dll. In your dll "h" file specify this:
// This is the Mfcdll1.h header file
// You should have some code created by the wizard, similar to the following:
#ifdef MYDLL_EXPORTS
#define MYDLL_API __declspec(dllexport)
#else
#define MYDLL_API __declspec(dllimport)
#endif
// This is the typedef for your callback function type:
typedef void (CALLBACK* MY_DLL_CALLBACK)
(
LPVOID lpParam,
LPCTSTR lpszMessage
);
class CMyDllApp : public CWinApp
{
public:
CMyDllApp();
// etc.
void SetCallBack(MY_DLL_CALLBACK pCallback, LPVOID pCallbackParm){m_pCallback = pCallback; m_pCallbackParm = pCallbackParm;}
private:
MY_DLL_CALLBACK m_pCallback;
LPVOID m_pCallbackParm;
};
MYDLL_API void SetCallBack(MY_DLL_CALLBACK pCallback, LPVOID pCallbackParm);
In your dll's cpp file specify this:
CMyDllApp::CMyDllApp()
{
m_pCallback = NULL;
m_pCallbackParm = NULL;
}
MYDLL_API void SetCallBack(MY_DLL_CALLBACK pCallback, LPVOID pCallbackParm)
{
theApp.SetCallBack(pCallback, pCallbackParm);
}
Now, if your dll wants to call the callback function, all you need to do is:
CMyDllApp::SendCallbackToTheCaller(LPCTSTR lpszMessage)
{
if(m_pCallback) (*(m_pCallback))(m_pCallbackParm, lpszMessage);
}
At this stage you have done coding in the dll. Now, all you need to do is specify the static callback function in your dialog that will update you Edit control, similar to this:
In the h file:
// TestDlg.h - My Test dialog with the Edit Control
CTestDlg: public CDialog
{
public:
static void CALLBACK StatusCallback(LPVOID lpParam, LPCTSTR lpszMessage);
};
In the cpp file:
BOOL CTestDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Insert this line along your stuff
::SetCallback((MY_DLL_CALLBACK)StatusCallback, (LPVOID)this);
}
void CALLBACK CTestDlg::StatusCallback(LPVOID lpParam, LPCTSTR lpszMessage)
{
CTestDlg* pTestDlg = reinterpret_cast<CTestDlg*>(lpParam);
ASSERT(pTestDlg!=NULL);
pTestDlg->m_edStatus.SetWindowText(lpszMessage);
}

Resources