Created
August 26, 2023 09:42
-
-
Save smourier/b5c3e1574116f50ccdf0e2223a661ee3 to your computer and use it in GitHub Desktop.
Set notepad's text using UI automation w/o setting the focus on it first
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void Main() | |
{ | |
// needs using UIAutomationClient; | |
// requires a reference to windows\system32\UIAutomationClient.dll | |
// and set Embed Interop Types to false for project reference | |
var root = new CUIAutomation8(); | |
// we want to *keep* the focus | |
root.AutoSetFocus = 0; // false | |
// notepad must be started | |
var notepad = Process.GetProcessesByName("notepad")[0]; | |
// get notepad window | |
var window = root.ElementFromHandle(notepad.MainWindowHandle); | |
// get notepad document element | |
var document = window.FindFirst(TreeScope.TreeScope_Descendants, root.CreatePropertyCondition(UIA_PropertyIds.UIA_ControlTypePropertyId, UIA_ControlTypeIds.UIA_DocumentControlTypeId)); | |
var text = (IUIAutomationTextPattern2)document.GetCurrentPattern(UIA_PatternIds.UIA_TextPattern2Id); | |
// get document text | |
var value = text.DocumentRange.GetText(int.MaxValue); | |
// get value pattern & set document value (add date...) | |
var pattern = (IUIAutomationValuePattern)document.GetCurrentPattern(UIA_PatternIds.UIA_ValuePatternId); | |
pattern.SetValue(value + " " + DateTime.Now); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment