ctypes-users Mailing List for ctypes (Page 3)
Brought to you by:
theller
You can subscribe to this list here.
2003 |
Jan
(3) |
Feb
(97) |
Mar
(38) |
Apr
(50) |
May
(68) |
Jun
(67) |
Jul
(184) |
Aug
(58) |
Sep
(30) |
Oct
(40) |
Nov
(41) |
Dec
(53) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2004 |
Jan
(81) |
Feb
(48) |
Mar
(35) |
Apr
(85) |
May
(47) |
Jun
(56) |
Jul
(60) |
Aug
(103) |
Sep
(46) |
Oct
(39) |
Nov
(19) |
Dec
(50) |
2005 |
Jan
(36) |
Feb
(65) |
Mar
(119) |
Apr
(132) |
May
(93) |
Jun
(71) |
Jul
(42) |
Aug
(69) |
Sep
(41) |
Oct
(61) |
Nov
(31) |
Dec
(42) |
2006 |
Jan
(59) |
Feb
(112) |
Mar
(60) |
Apr
(64) |
May
(116) |
Jun
(128) |
Jul
(68) |
Aug
(92) |
Sep
(58) |
Oct
(91) |
Nov
(73) |
Dec
(52) |
2007 |
Jan
(37) |
Feb
(59) |
Mar
(26) |
Apr
(30) |
May
(37) |
Jun
(25) |
Jul
(20) |
Aug
(54) |
Sep
(68) |
Oct
(16) |
Nov
(34) |
Dec
(34) |
2008 |
Jan
(72) |
Feb
(40) |
Mar
(25) |
Apr
(54) |
May
(61) |
Jun
(22) |
Jul
(41) |
Aug
(26) |
Sep
(26) |
Oct
(66) |
Nov
(42) |
Dec
(58) |
2009 |
Jan
(100) |
Feb
(48) |
Mar
(20) |
Apr
(13) |
May
(10) |
Jun
(33) |
Jul
(9) |
Aug
|
Sep
(17) |
Oct
(9) |
Nov
(4) |
Dec
(64) |
2010 |
Jan
(18) |
Feb
(8) |
Mar
(37) |
Apr
(14) |
May
(9) |
Jun
(21) |
Jul
(1) |
Aug
(18) |
Sep
(12) |
Oct
(8) |
Nov
(4) |
Dec
(4) |
2011 |
Jan
(31) |
Feb
(3) |
Mar
(6) |
Apr
(1) |
May
(10) |
Jun
(9) |
Jul
(16) |
Aug
(5) |
Sep
(1) |
Oct
(5) |
Nov
(1) |
Dec
(11) |
2012 |
Jan
(4) |
Feb
(8) |
Mar
(14) |
Apr
(1) |
May
(2) |
Jun
(1) |
Jul
|
Aug
(10) |
Sep
(5) |
Oct
|
Nov
(4) |
Dec
(2) |
2013 |
Jan
(2) |
Feb
|
Mar
(1) |
Apr
|
May
(4) |
Jun
|
Jul
(3) |
Aug
(5) |
Sep
(12) |
Oct
|
Nov
|
Dec
(3) |
2014 |
Jan
|
Feb
|
Mar
|
Apr
(4) |
May
|
Jun
(4) |
Jul
|
Aug
|
Sep
(5) |
Oct
|
Nov
|
Dec
(2) |
2015 |
Jan
|
Feb
|
Mar
(5) |
Apr
|
May
|
Jun
|
Jul
|
Aug
(3) |
Sep
|
Oct
(7) |
Nov
|
Dec
(2) |
2016 |
Jan
(3) |
Feb
(6) |
Mar
(3) |
Apr
|
May
|
Jun
(9) |
Jul
(2) |
Aug
(2) |
Sep
|
Oct
|
Nov
(28) |
Dec
(31) |
2017 |
Jan
|
Feb
|
Mar
|
Apr
(10) |
May
(28) |
Jun
(2) |
Jul
(3) |
Aug
(2) |
Sep
(4) |
Oct
(31) |
Nov
(2) |
Dec
|
2018 |
Jan
|
Feb
(1) |
Mar
(1) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: Michael C <mys...@gm...> - 2017-05-18 02:14:35
|
where can i read up on what a thread is and what it does? Thanks! On Wed, May 17, 2017 at 7:12 PM, eryk sun <er...@gm...> wrote: > On Wed, May 17, 2017 at 11:10 PM, Michael C > <mys...@gm...> wrote: > > Apparently even though the MSDN says, given a handle, it would kill the > > window, but it doesn't do that for me. Am I doing it properly? > > > > import time > > import ctypes > > User32 = ctypes.WinDLL('User32', use_last_error=True) > > > > handle = User32.GetForegroundWindow() > > print(handle) > > time.sleep(2) > > User32.DestroyWindow(handle) > > You're not checking the BOOL return value to see whether the call > succeeded. If it failed, you need to raise an exception for the > thread's last error value. Do this in a ctypes errcheck function. For > example: > > def _check_bool(result, func, args): > if not result: > raise ctypes.WinError(ctypes.get_last_error()) > return args > > User32.DestroyWindow.errcheck = _check_bool > > With this check in place, if User32.DestroyWindow(handle) fails, > you'll get an idiomatic exception. Chances are that the foreground > window doesn't belong to your thread, and you haven't read the fine > print in the remarks on MSDN: > > A thread cannot use DestroyWindow to destroy a window created by a > different thread. > > Thus it's probably failing with ERROR_ACCESS_DENIED (5). Try sending > the window a WM_CLOSE message instead. > |
From: eryk s. <er...@gm...> - 2017-05-18 02:13:15
|
On Wed, May 17, 2017 at 11:10 PM, Michael C <mys...@gm...> wrote: > Apparently even though the MSDN says, given a handle, it would kill the > window, but it doesn't do that for me. Am I doing it properly? > > import time > import ctypes > User32 = ctypes.WinDLL('User32', use_last_error=True) > > handle = User32.GetForegroundWindow() > print(handle) > time.sleep(2) > User32.DestroyWindow(handle) You're not checking the BOOL return value to see whether the call succeeded. If it failed, you need to raise an exception for the thread's last error value. Do this in a ctypes errcheck function. For example: def _check_bool(result, func, args): if not result: raise ctypes.WinError(ctypes.get_last_error()) return args User32.DestroyWindow.errcheck = _check_bool With this check in place, if User32.DestroyWindow(handle) fails, you'll get an idiomatic exception. Chances are that the foreground window doesn't belong to your thread, and you haven't read the fine print in the remarks on MSDN: A thread cannot use DestroyWindow to destroy a window created by a different thread. Thus it's probably failing with ERROR_ACCESS_DENIED (5). Try sending the window a WM_CLOSE message instead. |
From: Michael C <mys...@gm...> - 2017-05-17 23:10:35
|
Apparently even though the MSDN says, given a handle, it would kill the window, but it doesn't do that for me. Am I doing it properly? Thanks! import time import ctypes User32 = ctypes.WinDLL('User32', use_last_error=True) handle = User32.GetForegroundWindow() print(handle) time.sleep(2) User32.DestroyWindow(handle) |
From: Michael C <mys...@gm...> - 2017-05-16 19:15:19
|
ok! On Tue, May 16, 2017 at 12:12 PM, eryk sun <er...@gm...> wrote: > On Tue, May 16, 2017 at 6:50 PM, Michael C > <mys...@gm...> wrote: > > I am running this code so I can do some image manipulation with them. > > The thing is, I have a lot of pictures to go through, so I can't type the > > file names one by one in the code. However, the order of the files to be > > processed doesn't matter, so getting them in a random fashion is alright! > > > > How do I make the python code open picture files? thanks! > > > > ## need to open random png. Any png. > > > > from PIL import Image > > > > ## need to load picture so I can process them. Any pictures is fine as > > ## I need to process every picture in the folder > > im = Image.open('1.png') > > > > ## do my things... > > This questions isn't about ctypes. Please ask this on the python-tutor > list. > |
From: eryk s. <er...@gm...> - 2017-05-16 19:13:14
|
On Tue, May 16, 2017 at 6:50 PM, Michael C <mys...@gm...> wrote: > I am running this code so I can do some image manipulation with them. > The thing is, I have a lot of pictures to go through, so I can't type the > file names one by one in the code. However, the order of the files to be > processed doesn't matter, so getting them in a random fashion is alright! > > How do I make the python code open picture files? thanks! > > ## need to open random png. Any png. > > from PIL import Image > > ## need to load picture so I can process them. Any pictures is fine as > ## I need to process every picture in the folder > im = Image.open('1.png') > > ## do my things... This questions isn't about ctypes. Please ask this on the python-tutor list. |
From: Michael C <mys...@gm...> - 2017-05-16 18:50:40
|
I am running this code so I can do some image manipulation with them. The thing is, I have a lot of pictures to go through, so I can't type the file names one by one in the code. However, the order of the files to be processed doesn't matter, so getting them in a random fashion is alright! How do I make the python code open picture files? thanks! ## need to open random png. Any png. from PIL import Image ## need to load picture so I can process them. Any pictures is fine as ## I need to process every picture in the folder im = Image.open('1.png') ## do my things... |
From: Nicolas P. <nic...@aa...> - 2017-05-09 08:16:24
|
One way to do what you want is to create a process linked with your library. This process is the single access point to your C library. This process communicates with other processes (Pyhton and C#) through sockets, pipes or anything else. Le 04/05/2017 à 23:37, Zak Smolen a écrit : > Hi, > > I am trying to do something odd, and I was hoping someone may have > some ideas/guidance. > > My application has a C later, accessed by C# layers. I also have a > python wrapper for that C layer written using ctypes. I would like to > have the C# call python scripts which would then, using my library, do > things to the /same instance /of the C DLL as the C# is using. > > I know this is a complex task, but I feel like it should be possible. > After searching around the source code a bit I found a few things. On > my windows machine (windows-only is fine initially) it is using the > LoadLibrary function from kernel32. Also, the CDLL class is able to > take a handle pointer to use instead of calling LoadLibrary. > > So, I wrote this little wrapper function and I was able to pass in the > handle that the C# is using for the DLL so that the python is using > the same handle. That didn't seem to cut it. Anyone have any ideas > that may help with this task? > > Also, before you suggest it, I know about things like IronPython and > Python for .NET. The issues there are twofold: first, they are > restricted and don't have all libs, especially IronPython. Second, if > I want to use the python library, it still gets a different instance. > > Thanks, > Zak > > > ------------------------------------------------------------------------------ > Check out the vibrant tech community on one of the world's most > engaging tech sites, Slashdot.org! http://sdm.link/slashdot > > > _______________________________________________ > ctypes-users mailing list > cty...@li... > https://lists.sourceforge.net/lists/listinfo/ctypes-users -- *Nicolas PINAULT R&D electronics engineer *** ni...@aa... <mailto:ni...@aa...> *AATON-Digital* 38000 Grenoble - France Tel +33 4 7642 9550 http://www.aaton.com http://www.transvideo.eu French Technologies for Film and Digital Cinematography Follow us on Twitter @Aaton_Digital @Transvideo_HD Like us on Facebook https://www.facebook.com/AatonDigital |
From: Zak S. <zak...@gm...> - 2017-05-05 17:21:23
|
Huh, I always heard of Python for .NET as Python consuming a .NET DLL but it looks like the reverse is true as well. And it looks like it works with numpy according to their example code (IronPython doesn't really work with most of the science/math libs). I'll give that a go before I try accessing python DLLs. On Fri, May 5, 2017 at 12:45 PM, Zak Smolen <zak...@gm...> wrote: > Thanks for that clarification. Yeh it really seems like the only way to > truly get this to work is if it all happens from the same process. I'll > look into including python and see if that method works. Looking at my > code, my method of calling the python was in a new process, so that would > never really work. > > On Fri, May 5, 2017 at 10:52 AM, eryk sun <er...@gm...> wrote: > >> On Fri, May 5, 2017 at 1:52 PM, Zak Smolen <zak...@gm...> wrote: >> > So my thought behind this is that it must be possible... somehow, >> because of >> > debuggers. You can attach a debugger to an existing process and see it's >> > memory and such. I don't need simultaneous access from both the C# >> wrapper >> > and the python at the same time. I can have the C# not touch the C >> while the >> > python is running. It looks like debuggers do things with signals and >> such. >> >> Reading the memory of a process like a debugger is not much of a >> programming interface. ReadProcessMemory [1] requires a process handle >> with VM read access (e.g. your Python script would need a handle for >> the C# process). It's implemented by having the memory manager attach >> to the process, map the target address range into kernel space, and >> then attach to your process and copy that data to your buffer. >> WriteProcessMemory [2] requires a handle with VM write and operation >> access, and it's implemented in the opposite direction: map your >> buffer to kernel space and then attach to the target process and write >> the data at the target address. Considering these two address spaces >> are unrelated, you'd need some IPC scheme to send the base address to >> the process that wants to read from or write to memory in your >> process. >> >> If you want a section of shared memory, the DLL has to be designed >> around it from the start. As far as the code in the DLL is concerned >> it's just reading from and writing to a global variable at an address >> in the current process. But under the hood the pages (typically 4 KiB >> each) are shared with every process that loads the DLL, so they all >> access the same data. >> >> The alternative is to embed CPython in your .NET application. If >> Python for .NET is hosted out of process, then yes it will be a >> separate DLL instance. But you could still investigate directly >> loading pythonXX.dll in your process to run the interpreter and have >> ctypes (for whatever reason you need to do this in Python instead of >> C#) access the DLL in your current process. >> >> [1]: https://msdn.microsoft.com/en-us/library/ms680553 >> [2]: https://msdn.microsoft.com/en-us/library/ms681674 >> > > |
From: Zak S. <zak...@gm...> - 2017-05-05 16:45:34
|
Thanks for that clarification. Yeh it really seems like the only way to truly get this to work is if it all happens from the same process. I'll look into including python and see if that method works. Looking at my code, my method of calling the python was in a new process, so that would never really work. On Fri, May 5, 2017 at 10:52 AM, eryk sun <er...@gm...> wrote: > On Fri, May 5, 2017 at 1:52 PM, Zak Smolen <zak...@gm...> wrote: > > So my thought behind this is that it must be possible... somehow, > because of > > debuggers. You can attach a debugger to an existing process and see it's > > memory and such. I don't need simultaneous access from both the C# > wrapper > > and the python at the same time. I can have the C# not touch the C while > the > > python is running. It looks like debuggers do things with signals and > such. > > Reading the memory of a process like a debugger is not much of a > programming interface. ReadProcessMemory [1] requires a process handle > with VM read access (e.g. your Python script would need a handle for > the C# process). It's implemented by having the memory manager attach > to the process, map the target address range into kernel space, and > then attach to your process and copy that data to your buffer. > WriteProcessMemory [2] requires a handle with VM write and operation > access, and it's implemented in the opposite direction: map your > buffer to kernel space and then attach to the target process and write > the data at the target address. Considering these two address spaces > are unrelated, you'd need some IPC scheme to send the base address to > the process that wants to read from or write to memory in your > process. > > If you want a section of shared memory, the DLL has to be designed > around it from the start. As far as the code in the DLL is concerned > it's just reading from and writing to a global variable at an address > in the current process. But under the hood the pages (typically 4 KiB > each) are shared with every process that loads the DLL, so they all > access the same data. > > The alternative is to embed CPython in your .NET application. If > Python for .NET is hosted out of process, then yes it will be a > separate DLL instance. But you could still investigate directly > loading pythonXX.dll in your process to run the interpreter and have > ctypes (for whatever reason you need to do this in Python instead of > C#) access the DLL in your current process. > > [1]: https://msdn.microsoft.com/en-us/library/ms680553 > [2]: https://msdn.microsoft.com/en-us/library/ms681674 > |
From: eryk s. <er...@gm...> - 2017-05-05 14:53:05
|
On Fri, May 5, 2017 at 1:52 PM, Zak Smolen <zak...@gm...> wrote: > So my thought behind this is that it must be possible... somehow, because of > debuggers. You can attach a debugger to an existing process and see it's > memory and such. I don't need simultaneous access from both the C# wrapper > and the python at the same time. I can have the C# not touch the C while the > python is running. It looks like debuggers do things with signals and such. Reading the memory of a process like a debugger is not much of a programming interface. ReadProcessMemory [1] requires a process handle with VM read access (e.g. your Python script would need a handle for the C# process). It's implemented by having the memory manager attach to the process, map the target address range into kernel space, and then attach to your process and copy that data to your buffer. WriteProcessMemory [2] requires a handle with VM write and operation access, and it's implemented in the opposite direction: map your buffer to kernel space and then attach to the target process and write the data at the target address. Considering these two address spaces are unrelated, you'd need some IPC scheme to send the base address to the process that wants to read from or write to memory in your process. If you want a section of shared memory, the DLL has to be designed around it from the start. As far as the code in the DLL is concerned it's just reading from and writing to a global variable at an address in the current process. But under the hood the pages (typically 4 KiB each) are shared with every process that loads the DLL, so they all access the same data. The alternative is to embed CPython in your .NET application. If Python for .NET is hosted out of process, then yes it will be a separate DLL instance. But you could still investigate directly loading pythonXX.dll in your process to run the interpreter and have ctypes (for whatever reason you need to do this in Python instead of C#) access the DLL in your current process. [1]: https://msdn.microsoft.com/en-us/library/ms680553 [2]: https://msdn.microsoft.com/en-us/library/ms681674 |
From: Zak S. <zak...@gm...> - 2017-05-05 13:52:37
|
So my thought behind this is that it must be possible... somehow, because of debuggers. You can attach a debugger to an existing process and see it's memory and such. I don't need simultaneous access from both the C# wrapper and the python at the same time. I can have the C# not touch the C while the python is running. It looks like debuggers do things with signals and such. I believe the issue with python for .NET, is that, while the C# would call my python a little more directly, the python still gets its own instance of the DLL. Even if I used IronPython, with a totally integrated control, that is still the same issue. Thanks for your response! I'm starting to think it's impossible, but not quite ready to accept that... On Fri, May 5, 2017 at 12:45 AM, eryk sun <er...@gm...> wrote: > On Thu, May 4, 2017 at 9:37 PM, Zak Smolen <zak...@gm...> wrote: > > > > My application has a C later, accessed by C# layers. I also have a python > > wrapper for that C layer written using ctypes. I would like to have the > C# > > call python scripts which would then, using my library, do things to the > > same instance of the C DLL as the C# is using. > > A DLL can use a shared memory section (i.e. a #pragma data_seg with > the shared attribute) for data that's shared across all processes, but > otherwise its global data is private to each process. Use VMMap [1] to > look at how pages in the .data section are mapped in your DLL. > > [1]: https://technet.microsoft.com/en-us/sysinternals/vmmap.aspx > > > Also, the CDLL class is able to take a handle pointer to use instead of > > calling LoadLibrary. > > An HMODULE 'handle' is a pointer to the base address where the DLL is > mapped in the current process. It won't necessarily load at the same > address in every process. Even if it's mapped at the same address, its > global .data will be mapped to private pages. > > > Anyone have any ideas that may help with this task? > > You could look into embedding Python into you .NET process. I thought > Python for .NET did that, but I've never used it and rarely touch any > of the .NET universe. > > Alternatively, if you're the author of the DLL you could put the > global variables that need to be shared in a .shared section. But > there are restrictions on what can be shared. For example, each > process has its own address space, so sharing pointers should be > avoided. Also, most handles can't be shared (e.g. kernel handles such > as File handles are privately defined in the handle table of each > process). > |
From: eryk s. <er...@gm...> - 2017-05-05 04:45:50
|
On Thu, May 4, 2017 at 9:37 PM, Zak Smolen <zak...@gm...> wrote: > > My application has a C later, accessed by C# layers. I also have a python > wrapper for that C layer written using ctypes. I would like to have the C# > call python scripts which would then, using my library, do things to the > same instance of the C DLL as the C# is using. A DLL can use a shared memory section (i.e. a #pragma data_seg with the shared attribute) for data that's shared across all processes, but otherwise its global data is private to each process. Use VMMap [1] to look at how pages in the .data section are mapped in your DLL. [1]: https://technet.microsoft.com/en-us/sysinternals/vmmap.aspx > Also, the CDLL class is able to take a handle pointer to use instead of > calling LoadLibrary. An HMODULE 'handle' is a pointer to the base address where the DLL is mapped in the current process. It won't necessarily load at the same address in every process. Even if it's mapped at the same address, its global .data will be mapped to private pages. > Anyone have any ideas that may help with this task? You could look into embedding Python into you .NET process. I thought Python for .NET did that, but I've never used it and rarely touch any of the .NET universe. Alternatively, if you're the author of the DLL you could put the global variables that need to be shared in a .shared section. But there are restrictions on what can be shared. For example, each process has its own address space, so sharing pointers should be avoided. Also, most handles can't be shared (e.g. kernel handles such as File handles are privately defined in the handle table of each process). |
From: Zak S. <zak...@gm...> - 2017-05-04 21:37:42
|
Hi, I am trying to do something odd, and I was hoping someone may have some ideas/guidance. My application has a C later, accessed by C# layers. I also have a python wrapper for that C layer written using ctypes. I would like to have the C# call python scripts which would then, using my library, do things to the *same instance *of the C DLL as the C# is using. I know this is a complex task, but I feel like it should be possible. After searching around the source code a bit I found a few things. On my windows machine (windows-only is fine initially) it is using the LoadLibrary function from kernel32. Also, the CDLL class is able to take a handle pointer to use instead of calling LoadLibrary. So, I wrote this little wrapper function and I was able to pass in the handle that the C# is using for the DLL so that the python is using the same handle. That didn't seem to cut it. Anyone have any ideas that may help with this task? Also, before you suggest it, I know about things like IronPython and Python for .NET. The issues there are twofold: first, they are restricted and don't have all libs, especially IronPython. Second, if I want to use the python library, it still gets a different instance. Thanks, Zak |
From: Michael C <mys...@gm...> - 2017-05-04 04:37:50
|
roger that On Wed, May 3, 2017 at 9:36 PM eryk sun <er...@gm...> wrote: > On Thu, May 4, 2017 at 3:59 AM, Michael C > <mys...@gm...> wrote: > > Ah, so all I had to do was to use User32.FindWindowW > > That's no substitute for understanding why FindWindowW and FindWindowA > exist, how they're implemented in terms of the system ANSI and OEM > code pages, how they're used in C via the UNICODE macro and the TCHAR > type system, and the historical context. As your general knowledge > improves, you'll be able to answer most of your own questions. If all > you do is get shallow answers to narrow questions, then your ability > to problem solve and your toolset for approaching new problems won't > improve much at all. > |
From: eryk s. <er...@gm...> - 2017-05-04 04:36:57
|
On Thu, May 4, 2017 at 3:59 AM, Michael C <mys...@gm...> wrote: > Ah, so all I had to do was to use User32.FindWindowW That's no substitute for understanding why FindWindowW and FindWindowA exist, how they're implemented in terms of the system ANSI and OEM code pages, how they're used in C via the UNICODE macro and the TCHAR type system, and the historical context. As your general knowledge improves, you'll be able to answer most of your own questions. If all you do is get shallow answers to narrow questions, then your ability to problem solve and your toolset for approaching new problems won't improve much at all. |
From: eryk s. <er...@gm...> - 2017-05-04 03:55:30
|
On Thu, May 4, 2017 at 3:36 AM, Michael C <mys...@gm...> wrote: > how do you set unicode strings? > > unicode_String = ? My example showed that. A unicode string literal is prefixed by u, e.g. u"Spam Wars". In Python 3 this isn't necessary since its str strings are always Unicode. |
From: Michael C <mys...@gm...> - 2017-05-04 03:36:17
|
how do you set unicode strings? unicode_String = ? thanks! On Wed, May 3, 2017 at 7:53 PM, eryk sun <er...@gm...> wrote: > On Wed, May 3, 2017 at 11:19 PM, Michael C > <mys...@gm...> wrote: > > Hi all, I am trying to move the location and change the size of a window, > > but the User32.FindWindow function cannot be found! > > > > AttributeError: function 'FindWindow' not found > > Here's the prototype from MSDN [1]: > > HWND WINAPI FindWindow( > _In_opt_ LPCTSTR lpClassName, > _In_opt_ LPCTSTR lpWindowName > ); > > [1]: https://msdn.microsoft.com/en-us/library/ms633499 > > The string type is "LPCTSTR". That's a [L]ong [P]ointer (just a > pointer nowadays; there's no segmented addressing) to a [C]onstant > [T]CHAR [STR]ing. A TCHAR is a [T]ext CHAR ("T" could also mean > "typed) that depends on defining the UNICODE macro in C. If the macro > is defined, a TCHAR is a two-byte WCHAR, i.e. a [W]ide CHAR, and > otherwise it's a single-byte CHAR. The macro also determines the > definition of the "T" types. If defined, an LPCTSTR is in turn defined > as an LPCWSTR, and otherwise it's an LPCSTR. > > Historically this split is because single-byte and double-byte code > pages were the way text was localized in the 80s and 90s in MS-DOS and > versions of Windows that extend DOS, i.e. Windows 3.x and 9x. The > newer NT system (developed in 1988-93 and released in 1993 as Windows > NT 3.1) is based on Unicode internally and uses 16-bit WCHARs. > > When the NT designers updated the existing Win16 API to Win32, they > needed to support porting legacy Windows applications that use code > pages, so they developed this typing system based on the UNICODE > macro. Also, when the Win32 API itself was ported to DOS-based Windows > 95, there was only rudimentary Unicode support, so for a long time > even new applications were designed around code pages. Starting with > Windows XP, all versions of Windows use the NT kernel, and by Windows > Vista new functions appear that only support Unicode (e.g. > SetFileInformationByHandle). > > What the FindWindow prototype is not showing is that when Windows is > built it has to support programs compiled for both CHAR and WCHAR. For > most functions Windows NT uses WCHAR, so the CHAR implementation > decodes the string arguments and calls a common internal function. The > code page it decodes from is usually the system-locale ANSI codepage > (e.g. 1252 in the U.S. and Western Europe), with a couple of > exceptions. The file-system 'ANSI' API can be set to the system-locale > OEM codepage (e.g. 850 in Western Europe) via SetFileApisToOEM. Also, > the console 'ANSI' API defaults to OEM and can be set to any > single-byte or multi-byte code page separately for input and screen > buffers via SetConsoleCP and SetConsoleOutputCP. > > Whenever possible you should prefer calling the [W]ide-character > function to avoid writing locale-dependent code. > > That said, here are the actual FindWindow prototypes from the WinUser.h > header: > > WINUSERAPI > HWND > WINAPI > FindWindowA( > _In_opt_ LPCSTR lpClassName, > _In_opt_ LPCSTR lpWindowName); > > WINUSERAPI > HWND > WINAPI > FindWindowW( > _In_opt_ LPCWSTR lpClassName, > _In_opt_ LPCWSTR lpWindowName); > > #ifdef UNICODE > #define FindWindow FindWindowW > #else > #define FindWindow FindWindowA > #endif // !UNICODE > > Since ctypes works at the ABI (application binary interface) level > rather than API (application programmng interface), you need to use > the function names a module actually links with, i.e. either > FindWindowA for the [A]NSI implementation or FindWindowW for the > [W]ide-character implementation. > > Let's take a look at your code. > > > import ctypes > > User32 = ctypes.WinDLL('User32', use_last_error=True) > > window_name = 'Star Wars' > > handle = User32.FindWindow(None, window_name ) > > If you're using Python 3, then 'Star Wars' is a Unicode string, and > you should call FindWindowW. If you're using Python 2, then it's a > byte string, and you should call FindWindowA. But I don't recommend > the latter. You should be working with Unicode, i.e. u'Star Wars'. For > example: > > import ctypes > from ctypes import wintypes > > user32 = ctypes.WinDLL('user32', use_last_error=True) > > user32.FindWindowW.restype = wintypes.HWND > user32.FindWindowW.argtypes = (wintypes.LPCWSTR, > wintypes.LPCWSTR) > > if __name__ == '__main__': > import os > kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) > > window_name = u'Spam Wars' > os.system('title {}'.format(window_name)) > > handle = user32.FindWindowW(None, window_name) > if handle is None: > handle = user32.FindWindowW(None, > u'Administrator: {}'.format(window_name)) > > assert handle == kernel32.GetConsoleWindow() > > Another thing to consider is that if you've defined the FindWindowW > prototype, ctypes in Python 2 will automatically convert a byte-string > argument to Unicode. It uses the encoding and errors that are set by > ctypes.set_conversion_mode(encoding, errors), which defaults to > ('mbcs', 'ignore'). Python's 'mbcs' encoding is the system-locale ANSI > code page. This automatic conversion is not implemented in Python 3 > ctypes, in which case you should definitely be using Unicode. > |
From: eryk s. <er...@gm...> - 2017-05-04 02:54:10
|
On Wed, May 3, 2017 at 11:19 PM, Michael C <mys...@gm...> wrote: > Hi all, I am trying to move the location and change the size of a window, > but the User32.FindWindow function cannot be found! > > AttributeError: function 'FindWindow' not found Here's the prototype from MSDN [1]: HWND WINAPI FindWindow( _In_opt_ LPCTSTR lpClassName, _In_opt_ LPCTSTR lpWindowName ); [1]: https://msdn.microsoft.com/en-us/library/ms633499 The string type is "LPCTSTR". That's a [L]ong [P]ointer (just a pointer nowadays; there's no segmented addressing) to a [C]onstant [T]CHAR [STR]ing. A TCHAR is a [T]ext CHAR ("T" could also mean "typed) that depends on defining the UNICODE macro in C. If the macro is defined, a TCHAR is a two-byte WCHAR, i.e. a [W]ide CHAR, and otherwise it's a single-byte CHAR. The macro also determines the definition of the "T" types. If defined, an LPCTSTR is in turn defined as an LPCWSTR, and otherwise it's an LPCSTR. Historically this split is because single-byte and double-byte code pages were the way text was localized in the 80s and 90s in MS-DOS and versions of Windows that extend DOS, i.e. Windows 3.x and 9x. The newer NT system (developed in 1988-93 and released in 1993 as Windows NT 3.1) is based on Unicode internally and uses 16-bit WCHARs. When the NT designers updated the existing Win16 API to Win32, they needed to support porting legacy Windows applications that use code pages, so they developed this typing system based on the UNICODE macro. Also, when the Win32 API itself was ported to DOS-based Windows 95, there was only rudimentary Unicode support, so for a long time even new applications were designed around code pages. Starting with Windows XP, all versions of Windows use the NT kernel, and by Windows Vista new functions appear that only support Unicode (e.g. SetFileInformationByHandle). What the FindWindow prototype is not showing is that when Windows is built it has to support programs compiled for both CHAR and WCHAR. For most functions Windows NT uses WCHAR, so the CHAR implementation decodes the string arguments and calls a common internal function. The code page it decodes from is usually the system-locale ANSI codepage (e.g. 1252 in the U.S. and Western Europe), with a couple of exceptions. The file-system 'ANSI' API can be set to the system-locale OEM codepage (e.g. 850 in Western Europe) via SetFileApisToOEM. Also, the console 'ANSI' API defaults to OEM and can be set to any single-byte or multi-byte code page separately for input and screen buffers via SetConsoleCP and SetConsoleOutputCP. Whenever possible you should prefer calling the [W]ide-character function to avoid writing locale-dependent code. That said, here are the actual FindWindow prototypes from the WinUser.h header: WINUSERAPI HWND WINAPI FindWindowA( _In_opt_ LPCSTR lpClassName, _In_opt_ LPCSTR lpWindowName); WINUSERAPI HWND WINAPI FindWindowW( _In_opt_ LPCWSTR lpClassName, _In_opt_ LPCWSTR lpWindowName); #ifdef UNICODE #define FindWindow FindWindowW #else #define FindWindow FindWindowA #endif // !UNICODE Since ctypes works at the ABI (application binary interface) level rather than API (application programmng interface), you need to use the function names a module actually links with, i.e. either FindWindowA for the [A]NSI implementation or FindWindowW for the [W]ide-character implementation. Let's take a look at your code. > import ctypes > User32 = ctypes.WinDLL('User32', use_last_error=True) > window_name = 'Star Wars' > handle = User32.FindWindow(None, window_name ) If you're using Python 3, then 'Star Wars' is a Unicode string, and you should call FindWindowW. If you're using Python 2, then it's a byte string, and you should call FindWindowA. But I don't recommend the latter. You should be working with Unicode, i.e. u'Star Wars'. For example: import ctypes from ctypes import wintypes user32 = ctypes.WinDLL('user32', use_last_error=True) user32.FindWindowW.restype = wintypes.HWND user32.FindWindowW.argtypes = (wintypes.LPCWSTR, wintypes.LPCWSTR) if __name__ == '__main__': import os kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) window_name = u'Spam Wars' os.system('title {}'.format(window_name)) handle = user32.FindWindowW(None, window_name) if handle is None: handle = user32.FindWindowW(None, u'Administrator: {}'.format(window_name)) assert handle == kernel32.GetConsoleWindow() Another thing to consider is that if you've defined the FindWindowW prototype, ctypes in Python 2 will automatically convert a byte-string argument to Unicode. It uses the encoding and errors that are set by ctypes.set_conversion_mode(encoding, errors), which defaults to ('mbcs', 'ignore'). Python's 'mbcs' encoding is the system-locale ANSI code page. This automatic conversion is not implemented in Python 3 ctypes, in which case you should definitely be using Unicode. |
From: Michael C <mys...@gm...> - 2017-05-03 23:19:16
|
Hi all, I am trying to move the location and change the size of a window, but the User32.FindWindow function cannot be found! AttributeError: function 'FindWindow' not found import ctypes User32 = ctypes.WinDLL('User32', use_last_error=True) window_name = 'Star Wars' handle = User32.FindWindow(None, window_name ) print(handle) User32.MoveWindow(handle, 0, 0, 1440, 900, False) How do I fix this? Thanks! |
From: eryk s. <er...@gm...> - 2017-05-02 05:57:25
|
On Tue, May 2, 2017 at 3:03 AM, Michael C <mys...@gm...> wrote: > holy cow The code for a global keyboard hook is a bit complex - mostly because I had to use ctypes (properly instead of an unreliable hack). Normally an application has one or more windows and a message loop, in which case there's no need for such an awkward approach. But you're asking to do this from a console application, which doesn't own a window. The window procedure that gets keyboard input from the system is in the console host process (conhost.exe). It processes input as a sequence of events that it stores in its input buffer. Thus you could use the input buffer instead of a global keyboard hook, but that comes with its own set of problems. You're no longer getting notified as soon as the character is typed in the window. Instead, the escape-key monitor has to share the input buffer with the main application. Events can be read without removing them via PeekConsoleInput, or read and removed via ReadConsoleInput. They can also be flushed (discarded) via FlushConsoleInputBuffer. If your script doesn't read from the console and the escape-key monitory only peeks the input buffer, it will grow without bound. However, it shouldn't read or flush input events that the main task needs, and the main task shouldn't read events that causes the escape-key monitoring thread to miss the user pressing escape. It needs an integrated design. |
From: Michael C <mys...@gm...> - 2017-05-02 03:03:44
|
holy cow On Mon, May 1, 2017 at 8:02 PM eryk sun <er...@gm...> wrote: > On Mon, May 1, 2017 at 6:28 PM, Michael C > <mys...@gm...> wrote: > > Hi all, I found out that one way to press ESC to kill the script was to > use > > my previous > > script language, AutoHotKey and this is how it works: > > > > AutoHotKey code > > ## function that kills the window with title '*Python 3.6.1 Shell*' > > > > kill() > > { > > WinKill, *Python 3.6.1 Shell* > > } > > > > ## When ESC is pressed, runs the function 'kill' > > Esc::kill() > > > > Yes, that's the entire script. > > Is there a way to write it in Python on windows? > > Instead of using a hotkey, you can set a global low-level keyboard > hook. Then optionally you can check for a particular foreground window > before handling the key. For example: > > import ctypes > import win32con > import win32gui > > from ctypes import wintypes > > user32 = ctypes.WinDLL('user32', use_last_error=True) > > VK_ESCAPE = 0x1B > > LLKHF_EXTENDED = 0x00000001 > LLKHF_LOWER_IL_INJECTED = 0x00000002 > LLKHF_INJECTED = 0x00000010 > LLKHF_ALTDOWN = 0x00000020 > LLKHF_UP = 0x00000080 > > ULONG_PTR = wintypes.WPARAM > class KBDLLHOOKSTRUCT(ctypes.Structure): > _fields_ = (('vkCode', wintypes.DWORD), > ('scanCode', wintypes.DWORD), > ('flags', wintypes.DWORD), > ('time', wintypes.DWORD), > ('dwExtraInfo', ULONG_PTR)) > > HOOKPROC = ctypes.WINFUNCTYPE(wintypes.LPARAM, ctypes.c_int, > wintypes.WPARAM, wintypes.LPARAM) > > user32.SetWindowsHookExW.restype = wintypes.HHOOK > user32.SetWindowsHookExW.argtypes = ( > ctypes.c_int, # _In_ idHook > HOOKPROC, # _In_ lpfn > wintypes.HINSTANCE, # _In_ hMod > wintypes.DWORD) # _In_ dwThreadId > > user32.CallNextHookEx.restype = wintypes.LPARAM > user32.CallNextHookEx.argtypes = ( > wintypes.HHOOK, # _In_opt_ hhk > ctypes.c_int, # _In_ nCode > wintypes.WPARAM, # _In_ wParam > wintypes.LPARAM) # _In_ lParam > > def keyboard_hook(handler, hwnd=None): > @HOOKPROC > def hookfunc(nCode, wParam, lParam): > event = KBDLLHOOKSTRUCT.from_address(lParam) > if hwnd is not None and win32gui.GetForegroundWindow() == hwnd: > handler(event) > return user32.CallNextHookEx(hHook, nCode, wParam, lParam) > > hHook = user32.SetWindowsHookExW(win32con.WH_KEYBOARD_LL, hookfunc, > None, 0) > if not hHook: > raise ctypes.WinError(ctypes.get_last_error()) > > win32gui.PumpMessages() > > if __name__ == '__main__': > import msvcrt > import threading > import win32console > > print('Press escape to quit') > > def escape_handler(event): > if event.vkCode == VK_ESCAPE: > # kill the hook thread > win32gui.PostQuitMessage(0) > elif not (event.flags & LLKHF_UP): > print('Virtual Key Code: {:#04x} [{}]'.format(event.vkCode, > event.time)) > > t = threading.Thread(target=keyboard_hook, args=(escape_handler, > win32console.GetConsoleWindow()), daemon=True) > t.start() > > # consume keyboard input > while t.is_alive(): > if msvcrt.kbhit(): > msvcrt.getwch() > > The __main__ demo should be run as a console script. The keyboard hook > filters on the console window handle from GetConsoleWindow(). > |
From: eryk s. <er...@gm...> - 2017-05-02 03:02:52
|
On Mon, May 1, 2017 at 6:28 PM, Michael C <mys...@gm...> wrote: > Hi all, I found out that one way to press ESC to kill the script was to use > my previous > script language, AutoHotKey and this is how it works: > > AutoHotKey code > ## function that kills the window with title '*Python 3.6.1 Shell*' > > kill() > { > WinKill, *Python 3.6.1 Shell* > } > > ## When ESC is pressed, runs the function 'kill' > Esc::kill() > > Yes, that's the entire script. > Is there a way to write it in Python on windows? Instead of using a hotkey, you can set a global low-level keyboard hook. Then optionally you can check for a particular foreground window before handling the key. For example: import ctypes import win32con import win32gui from ctypes import wintypes user32 = ctypes.WinDLL('user32', use_last_error=True) VK_ESCAPE = 0x1B LLKHF_EXTENDED = 0x00000001 LLKHF_LOWER_IL_INJECTED = 0x00000002 LLKHF_INJECTED = 0x00000010 LLKHF_ALTDOWN = 0x00000020 LLKHF_UP = 0x00000080 ULONG_PTR = wintypes.WPARAM class KBDLLHOOKSTRUCT(ctypes.Structure): _fields_ = (('vkCode', wintypes.DWORD), ('scanCode', wintypes.DWORD), ('flags', wintypes.DWORD), ('time', wintypes.DWORD), ('dwExtraInfo', ULONG_PTR)) HOOKPROC = ctypes.WINFUNCTYPE(wintypes.LPARAM, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM) user32.SetWindowsHookExW.restype = wintypes.HHOOK user32.SetWindowsHookExW.argtypes = ( ctypes.c_int, # _In_ idHook HOOKPROC, # _In_ lpfn wintypes.HINSTANCE, # _In_ hMod wintypes.DWORD) # _In_ dwThreadId user32.CallNextHookEx.restype = wintypes.LPARAM user32.CallNextHookEx.argtypes = ( wintypes.HHOOK, # _In_opt_ hhk ctypes.c_int, # _In_ nCode wintypes.WPARAM, # _In_ wParam wintypes.LPARAM) # _In_ lParam def keyboard_hook(handler, hwnd=None): @HOOKPROC def hookfunc(nCode, wParam, lParam): event = KBDLLHOOKSTRUCT.from_address(lParam) if hwnd is not None and win32gui.GetForegroundWindow() == hwnd: handler(event) return user32.CallNextHookEx(hHook, nCode, wParam, lParam) hHook = user32.SetWindowsHookExW(win32con.WH_KEYBOARD_LL, hookfunc, None, 0) if not hHook: raise ctypes.WinError(ctypes.get_last_error()) win32gui.PumpMessages() if __name__ == '__main__': import msvcrt import threading import win32console print('Press escape to quit') def escape_handler(event): if event.vkCode == VK_ESCAPE: # kill the hook thread win32gui.PostQuitMessage(0) elif not (event.flags & LLKHF_UP): print('Virtual Key Code: {:#04x} [{}]'.format(event.vkCode, event.time)) t = threading.Thread(target=keyboard_hook, args=(escape_handler, win32console.GetConsoleWindow()), daemon=True) t.start() # consume keyboard input while t.is_alive(): if msvcrt.kbhit(): msvcrt.getwch() The __main__ demo should be run as a console script. The keyboard hook filters on the console window handle from GetConsoleWindow(). |
From: Michael C <mys...@gm...> - 2017-05-01 18:28:36
|
Hi all, I found out that one way to press ESC to kill the script was to use my previous script language, AutoHotKey and this is how it works: AutoHotKey code ## function that kills the window with title '*Python 3.6.1 Shell*' kill() { WinKill, *Python 3.6.1 Shell* } ## When ESC is pressed, runs the function 'kill' Esc::kill() Yes, that's the entire script. Is there a way to write it in Python on windows? Thanks! |
From: Michael C <mys...@gm...> - 2017-05-01 18:10:26
|
Hi all, I am trying to write a script to exit itself when ESC is pressed. I have found several answers regarding it such as this: http://stackoverflow.com/questions/43709710/push-esc-to-terminate-python-script?noredirect=1#comment74464169_43709710 But those only work when the program goes to that point. Is there a way to write it so that it would run exit() even when the program is in the background? Thanks! |
From: eryk s. <er...@gm...> - 2017-04-29 00:35:40
|
On Sat, Apr 29, 2017 at 12:28 AM, Michael C <mys...@gm...> wrote: > > I have my own code that samples pixel colour, > https://pastebin.com/4EMd765h > > and now I am trying to add the feature of saving the Device Context to a > .bmp file, so I found this code > > https://books.google.ca/books?id=9MS9BQAAQBAJ > > however there is one problem: The book example screenshots the whole desktop > and I only want a screenshot of a given window. Is there a way to modify the > black hat example into something that only screenshot a window given its > handle? This is a general WinAPI question, so if you don't mind, could you please ask it on the python-win32 list instead? https://mail.python.org/mailman/listinfo/python-win32 |