I am trying to get windows message box pop in front but every time the message box is called it just pops up in the background on another monitor.
import ctypes
from time import sleep
sleep(5) # for switching to another window
MB_SETFOREGROUND = 0x10000
ctypes.windll.user32.MessageBoxW(None, "This should be in top", "Very important messsage", MB_SETFOREGROUND)
Using MB_SYSTEMMODAL worked to bring the window to the front.
import ctypes
from time import sleep
sleep(5) # for switching to another window
MB_SYSTEMMODAL = 0x00001000
ctypes.windll.user32.MessageBoxW(None, "This should be in top", "Very important message", MB_SYSTEMMODAL)
I always recommend using .argtypes and .restype to ensure parameters are marshaled correctly between Python and C and it allows ctypes to better error check parameters:
import ctypes as ct
import ctypes.wintypes as w
import time
dll = ct.WinDLL('user32', use_last_error=True)
dll.MessageBoxW.argtypes = w.HWND, w.LPCWSTR, w.LPCWSTR, w.UINT
dll.MessageBoxW.restype = ct.c_int
MB_SYSTEMMODAL = 0x00001000
IDOK = 1
print('Waiting...')
time.sleep(5)
result = dll.MessageBoxW(None, "This should be in top", "Very important message", MB_SYSTEMMODAL)
print(result == IDOK)
Related
i'm trying to do (what should be) some minor work with win32. I basically just need to send a message and wait for a response.
I need the HWND or window handle of my python script/program to actually send the message.
I need to receive a WM_COPYDATA message from the end program.
I'm able to find the HWND of my python program with a script provided by ColonelFai1ure#0706 on the python discord server:
#gets the HWND of the active window
def getActiveWinID():
print(ctypes.windll.user32.GetForegroundWindow())
return ctypes.windll.user32.GetForegroundWindow()
Although I have to keep my PyCharm instance as the active window, it works fine, i'm able to send a message with the HWND now!
So I send a message with:
import ctypes
import subprocess # can be async
from ctypes import wintypes
from ctypes import *
with subprocess.Popen(r"C:\Users\lafft\Downloads\2021-04-11\3.35\ProxyTool\ProxyAPI.exe "
r"-changeproxy/US/NY/'New York' -citynolimit -proxyport=5001 -hwnd=330320",
stdin=subprocess.PIPE, stdout=subprocess.PIPE) as process:
for line in process.stdout:
print(line)
It works! The end program receives my message and performs the work I need it to do, this is the output:
b'Api executed successfully.\r\n'
Now I need to receive WM_COPYDATA from the end program to my hwnd, I modified some py2 code I found here:
class ACOPYDATASTRUCT(Structure):
_fields_ = [
('dwData', c_ulong),
('cbData', c_ulong),
('lpData', c_void_p)
]
PCOPYDATASTRUCT = POINTER(ACOPYDATASTRUCT)
class Listener:
def __init__(self):
message_map = {
win32con.WM_COPYDATA: self.OnCopyData
}
wc = win32gui.WNDCLASS()
wc.lpfnWndProc = message_map
wc.lpszClassName = 'MyWindowClass'
hinst = wc.hInstance = win32api.GetModuleHandle(None)
classAtom = win32gui.RegisterClass(wc)
self.hwnd = 330320
print(self.hwnd)
def OnCopyData(self, hwnd, msg, wparam, lparam):
print(hwnd)
print(msg)
print(wparam)
print(lparam)
pCDS = cast(lparam, PCOPYDATASTRUCT)
print(pCDS.contents.dwData)
print(pCDS.contents.cbData)
status = wstring_at(pCDS.contents.lpData)
print(status)
win32gui.PostQuitMessage(0)
return 1
l = Listener()
win32gui.PumpMessages()
Unfortunately, the message never comes in. I'm using PyCharm to run this, if it makes a difference.
I have 0 idea what to do now, and tutorials on the internet for this is sparse or written in python 2. Any help is appreciated, a link to a tutorial, some code, anything.
how to make that every 10 sec automatically change the program background
and the colors will be randomly selected
color = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
update:
i want use in this code:
app = wx.App()
window = wx.Frame(None, title = "test con", size=(800,300) )
window.SetMaxSize(wx.Size(800,300))
window.SetMinSize(wx.Size(800,300))
window.SetIcon(wx.Icon("eq.ico"))
window.SetBackgroundColour(color)
panel = wx.Panel(window, wx.ID_ANY)
suka = bat()
def on_timer():
label1aa.SetLabel(str(ram_uz()))
label8.SetLabel(doi)
label16.SetLabel(str(random.randint(1,100)))
label1a.SetLabel(str(bat()))
wx.CallLater(1000, on_timer)
panel.SetBackgroundColour(color)
panel.SetCursor(wx.Cursor(wx.CURSOR_HAND))
try this i hope it will help you
import threading
def change_color():
while True:
time.sleep(10)
color = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
threading.Thread(target=change_color).start()
You could use a timer:
import threading
timer = threading.Timer(interval, function)
//interval is the lapse of time you want between each execution of the function "function"
timer.start()
I'm trying to get the Window ID of the SDL window, to give to VLC so it can play the video in the window.
Being new to Python, I'm vaguely aware this has to do with variable type conversions to play nice with SDL, and using the correct python binding...
The line with the error is "win_id = SDL_GetWindowID(window)"
Here is my code;
import sys
import sdl2.ext
import vlc
import ctypes
from sdl2 import *
RESOURCES = sdl2.ext.Resources(__file__, "resources")
sdl2.ext.init()
window = sdl2.ext.Window("Hello World!", size=(640, 480))
window.show()
factory = sdl2.ext.SpriteFactory(sdl2.ext.SOFTWARE)
sprite = factory.from_image(RESOURCES.get_path("hello.bmp"))
spriterenderer = factory.create_sprite_render_system(window)
spriterenderer.render(sprite)
vlcInstance = vlc.Instance("--no-xlib")
player = vlcInstance.media_player_new()
win_id = SDL_GetWindowID(window)
player.set_xwindow(win_id)
player.set_mrl("agro.mp4")
player.play()
processor = sdl2.ext.TestEventProcessor()
processor.run(window)
sdl2.ext.quit()
What you get with SDL_GetWindowID is SDL's internal window ID that it itself refers to in e.g. events. What you need is X11 window ID, which you can get through SDL_GetWindowWMInfo. That however requires some trickery with SDL versioning, e.g. (I'm not sure it is safe to call that in python if SDL version changes but pysdl2 is not updated):
wminfo = SDL_SysWMinfo();
SDL_GetVersion(wminfo.version);
if(SDL_GetWindowWMInfo(window.window, wminfo) == 0):
print("can't get SDL WM info");
sys.exit(1);
win_id = wminfo.info.x11.window;
Then use that win_id to feed to vlc.
So I'm creating a small program using Oython / GTK+, at it's core is a WebView which displays some HTML-page. I now want to allow the user to manipulate the view by highlighting text, underline text etc. Later I want my program to store this markup in a different file, so it can dynamically be loaded at a later time.
I could simply set the WebView as editable, but then I have to save a changed HTML-document; I rather want to leave the original document untouched and save the user-markup seperately.
My idea was to use the DOM, esp. the DOMDOMSelection and DOMRange functions. The WebKit3.0 API (here) states that
WebKitViewer.get_dom_document()
should return a WebKit.DOMDocument. However, as running the attached MWE (below) shows, this call returns a WebKit.DOMHTMLDocument.
Using this object I don't find a way to access the DOMDocument or DOMDOMSelection I would need to proceed further.
My question:
Q: Is it a known bug or am I using the wrong calls?
EDIT1:
While I am not sure if the return value mentioned above is correct, I found a way to circumwent my problem:
# The still strange return document
DOMHTMLdoc = editor.get_dom_document()
# The view that contains the doc
def_view = DOMHTMLdoc.get_default_view()
# On this view one can finally create a selection
sel = def_view.get_selection()
END_EDIT1
If there is another (easier) way to achive this I'm open for suggestions ;)
Thanks in advance.
Setup:
Linux Antergos 4.9.11-1-ARCH x86_64
Geany
Python3.6.0
gir1.0
MWE
import gi
import os
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit', '3.0')
from gi.repository import Gtk, WebKit
w = Gtk.Window()
w.set_title("Example Editor")
w.set_default_size(800,400)
w.connect("destroy", Gtk.main_quit)
message = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><title>ERSTE SCHRITTE MIT BRACKETS</title><meta name=\"description\" content=\"Ein interaktiver Wegweiser für die ersten Schritte mit Brackets.\"><link rel=\"stylesheet\" href=\"main.css\"></head><body><h1>ERSTE SCHRITTE MIT BRACKETS</h1><h2>Dies ist Ihre Anleitung!</h2><p> Willkommen zu Brackets, einem modernen, quelloffenen Code-Editor, der Webdesign versteht. Es ist ein einfacher, aber dennoch leistungsfähiger Editor, der Ihnen immer die richtigen Tools einblendet, sodass Sie die genau richtige Menge an Hilfestellung haben, wann immer Sie diese brauchen.</p></body></html>"
editor = WebKit.WebView()
status = editor.get_load_status()
DOMHTMLdoc = editor.get_dom_document()
def load_up(self):
editor.load_string(message,"text/html","utf-8","file://")
def show_status(self):
# Give the WebView some time to load everything
status = editor.get_load_status()
if status == 2:
# Here I would expect a DOMDocument to be returned
# but instead I get DOMHTMLDocument
DOMHTMLdoc = editor.get_dom_document()
el = DOMHTMLdoc.get_active_element()
coll = el.get_children()
length = coll.get_length()
print("DOMHTMLdoc: ")
print(DOMHTMLdoc)
# Here I can loop over the elements, but always DOMHTMLxx
print("DOMHTMLElement: ")
print(el)
for i in range(0, length):
print(coll.item(i))
hb = Gtk.HBox()
vb = Gtk.VBox()
b = Gtk.Button("Load")
b.connect("clicked", load_up)
b2 = Gtk.Button("DOM status")
b2.connect("clicked", show_status)
swindow = Gtk.ScrolledWindow()
swindow.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
swindow.add(editor)
hb.add(b)
hb.add(b2)
vb.pack_start(hb, False, False, 0)
vb.add(swindow)
w.add(vb)
w.show_all()
Gtk.main()
I am trying to implement a single tkinter button which should "tail -f" some log file in a remote server. It should also stop the process locally AND kill the remote tail process when it is clicked for the second time. I tried this by not using tkinter with success.It stops when ctrl c is pressed.
When the tail(button3) button is clicked it hangs and it waits for the job completed. It is not accepting any new events until then. I know tkinter is single threaded and believe this is causing the issue. Code is below, appreciate any help.
from Tkinter import *
from re import *
import paramiko
import time
import select
class MyApp:
def __init__(self, parent):
self.myParent = parent
self.myContainer1 = Frame(parent,width=500,height=500)
self.myContainer1.pack()
#------------------ LABEL #1 for MAC ------------------------------------
#mac label field
self.label = Label (self.myContainer1, text='enter MAC').pack(side=TOP,padx=10,pady=10)
#------------------ ENTRY FIELD #1 for MAC ------------------------------------
#mac entry field
mac_var=StringVar()
self.entry = Entry(self.myContainer1,textvariable= mac_var ,width=10)
self.entry.pack(side=TOP,padx=100,pady=10)
mac_var.set("XXXXX")
s=mac_var.get()
#------------------ LABEL #2 for MAC OWNER ------------------------------------
#name label field
self.label = Label (self.myContainer1, text='enter MAC owner').pack(side=TOP,padx=10,pady=10)
#------------------ ENTRY #2 for MAC OWNER ------------------------------------
#name entry field
name_var=StringVar()
self.entry = Entry(self.myContainer1,textvariable= name_var ,width=25)
self.entry.pack(side=TOP,padx=100,pady=10)
name_var.set("name surname")
s=name_var.get()
#------------------ BUTTON #3 ------------------------------------
# event binding
self.button3 = Button(self.myContainer1)
self.button3.bind("<Button-1>", self.button3Click)
self.button3.configure(text="tail", background="purple")
self.button3.pack(side=LEFT)
def button3Click(self, event):
if self.button3["background"] == "purple":
self.button3.configure(text="Cancel Tail", background="yellow")
self.tail_flag=True
print "tail_flag is" , self.tail_flag
self.taillogg()
else:
self.button3.configure(text="Tail", background="purple")
self.canceltaillogg()
#root.destroy()
def canceltaillogg(self):
self.tail_flag=False
print "tail_flag is" , self.tail_flag
def taillogg(self):
server, port, username, password = ('myserver', 22, 'root', 'passw')
paramiko.util.log_to_file("C:\\log_transport_paramiko.txt")
nbytes = 100
trans = paramiko.Transport((server, port))
trans.connect(username = username, password = password)
trans.set_keepalive(1) # when ssh dies (with Ctrl C) processes spawned by that ssh connections will die, too ( in one sec)
sess = trans.open_channel("session")
#Once the channel is established, we can execute only one command.
#To execute another command, we need to create another channel
sess.exec_command('tail -f /usr/local/var/log/radius/radius.log')
timeout = 10
timestart =time.time()
while True:
try:
rl, wl, xl = select.select([sess],[],[],0.0)
if len(rl) > 0: #stdout
print sess.recv(1024)
if time.time()-timestart > timeout or self.tail_flag==False :
print "timeout 30 sec"
trans.close()
sess.close()
break
except KeyboardInterrupt :
print("Caught Control-C")
trans.close()
sess.close()
break
"""if self.tail_flag==False:
break"""
print ("\n")*100 # clear the screen
print "Starting program"
root = Tk()
root.title('MAC REGISTRATION APPLET')
myapp = MyApp(root)
print ("Ready to start executing the event loop.")
root.mainloop()
print ("Finished executing the event loop.")
Try this - see if it gives you the behavior your want.
self.button3.bind("<Button-1>", lambda:self.root.after(0, self.button3Click)
Also, this is unrelated, but you don't have to call "bind" on your button - it has a built in callback attribute called command:
self.button3 = Button(self.myContainer1, command=lambda:self.root.after(0, self.button3Click))
# self.button3.bind("<Button-1>", self.button3Click) (don't need this)
Then you'll want to remove the event argument from the button3Click function, since the button callback doesn't receive any arguments.