├── .coveragerc ├── .gitignore ├── LICENSE.txt ├── MANIFEST.in ├── README.md ├── code_of_conduct.md ├── docs ├── Makefile ├── conf.py ├── index.rst └── make.bat ├── pyproject.toml ├── setup.py ├── src └── nicewin │ ├── __init__.py │ ├── constants.py │ └── structs.py ├── tests └── test_nicewin.py └── tox.ini /.coveragerc: -------------------------------------------------------------------------------- 1 | # .coveragerc to control coverage.py 2 | 3 | # To run coverage tests, run `coverage run tests/test_nicewin.py` then `coverage html`. The report will be in htmlconv/index.html 4 | 5 | 6 | 7 | [run] 8 | 9 | 10 | 11 | [report] 12 | # Regexes for lines to exclude from consideration 13 | exclude_lines = 14 | # Have to re-enable the standard pragma 15 | pragma: no cover 16 | 17 | # Don't complain if tests don't hit defensive assertion code: 18 | raise AssertionError 19 | raise NotImplementedError 20 | 21 | # Don't complain if non-runnable code isn't run: 22 | if 0: 23 | if __name__ == .__main__.: 24 | 25 | ignore_errors = True 26 | 27 | 28 | [html] 29 | directory = htmlcov 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # OSX useful to ignore 7 | *.DS_Store 8 | .AppleDouble 9 | .LSOverride 10 | 11 | # Thumbnails 12 | ._* 13 | 14 | # Files that might appear in the root of a volume 15 | .DocumentRevisions-V100 16 | .fseventsd 17 | .Spotlight-V100 18 | .TemporaryItems 19 | .Trashes 20 | .VolumeIcon.icns 21 | .com.apple.timemachine.donotpresent 22 | 23 | # Directories potentially created on remote AFP share 24 | .AppleDB 25 | .AppleDesktop 26 | Network Trash Folder 27 | Temporary Items 28 | .apdisk 29 | 30 | # C extensions 31 | *.so 32 | 33 | # Distribution / packaging 34 | .Python 35 | env/ 36 | build/ 37 | develop-eggs/ 38 | dist/ 39 | downloads/ 40 | eggs/ 41 | .eggs/ 42 | lib/ 43 | lib64/ 44 | parts/ 45 | sdist/ 46 | var/ 47 | *.egg-info/ 48 | .installed.cfg 49 | *.egg 50 | 51 | # PyInstaller 52 | # Usually these files are written by a python script from a template 53 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 54 | *.manifest 55 | *.spec 56 | 57 | # Installer logs 58 | pip-log.txt 59 | pip-delete-this-directory.txt 60 | 61 | # Unit test / coverage reports 62 | htmlcov/ 63 | .tox/ 64 | .coverage 65 | .coverage.* 66 | .cache 67 | nosetests.xml 68 | coverage.xml 69 | *,cover 70 | .hypothesis/ 71 | .pytest_cache/ 72 | 73 | # Translations 74 | *.mo 75 | *.pot 76 | 77 | # Django stuff: 78 | *.log 79 | 80 | # Sphinx documentation 81 | docs/_build/ 82 | 83 | # IntelliJ Idea family of suites 84 | .idea 85 | *.iml 86 | ## File-based project format: 87 | *.ipr 88 | *.iws 89 | ## mpeltonen/sbt-idea plugin 90 | .idea_modules/ 91 | 92 | # PyBuilder 93 | target/ 94 | 95 | # Cookiecutter 96 | output/ 97 | python_boilerplate/ 98 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nicewin 2 | A nicely-documented, pure-Python wrapper for the Windows API for Python 2 and 3. 3 | 4 | Support 5 | ------- 6 | 7 | If you find this project helpful and would like to support its development, [consider donating to its creator on Patreon](https://www.patreon.com/AlSweigart). 8 | -------------------------------------------------------------------------------- /code_of_conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team. 59 | 60 | All complaints will be reviewed and investigated and will result in a response that 61 | is deemed necessary and appropriate to the circumstances. The project team is 62 | obligated to maintain confidentiality with regard to the reporter of an incident. 63 | Further details of specific enforcement policies may be posted separately. 64 | 65 | Project maintainers who do not follow or enforce the Code of Conduct in good 66 | faith may face temporary or permanent repercussions as determined by other 67 | members of the project's leadership. 68 | 69 | ## Attribution 70 | 71 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 72 | available at [http://contributor-covenant.org/version/1/4][version] 73 | 74 | [homepage]: http://contributor-covenant.org 75 | [version]: http://contributor-covenant.org/version/1/4/ -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SOURCEDIR = . 8 | BUILDDIR = _build 9 | 10 | # Put it first so that "make" without argument is like "make help". 11 | help: 12 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 13 | 14 | .PHONY: help Makefile 15 | 16 | # Catch-all target: route all unknown targets to Sphinx using the new 17 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 18 | %: Makefile 19 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Configuration file for the Sphinx documentation builder. 4 | # 5 | # This file does only contain a selection of the most common options. For a 6 | # full list see the documentation: 7 | # http://www.sphinx-doc.org/en/master/config 8 | 9 | # -- Path setup -------------------------------------------------------------- 10 | 11 | # If extensions (or modules to document with autodoc) are in another directory, 12 | # add these directories to sys.path here. If the directory is relative to the 13 | # documentation root, use os.path.abspath to make it absolute, like shown here. 14 | # 15 | # import os 16 | # import sys 17 | # sys.path.insert(0, os.path.abspath('.')) 18 | 19 | 20 | # -- Project information ----------------------------------------------------- 21 | 22 | project = 'Nice Win' 23 | copyright = '2018, Al Sweigart' 24 | author = 'Al Sweigart' 25 | 26 | # The short X.Y version 27 | version = '' 28 | # The full version, including alpha/beta/rc tags 29 | release = '' 30 | 31 | 32 | # -- General configuration --------------------------------------------------- 33 | 34 | # If your documentation needs a minimal Sphinx version, state it here. 35 | # 36 | # needs_sphinx = '1.0' 37 | 38 | # Add any Sphinx extension module names here, as strings. They can be 39 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 40 | # ones. 41 | extensions = [ 42 | 'sphinx.ext.autodoc', 43 | 'sphinx.ext.doctest', 44 | 'sphinx.ext.coverage', 45 | ] 46 | 47 | # Add any paths that contain templates here, relative to this directory. 48 | templates_path = ['_templates'] 49 | 50 | # The suffix(es) of source filenames. 51 | # You can specify multiple suffix as a list of string: 52 | # 53 | # source_suffix = ['.rst', '.md'] 54 | source_suffix = '.rst' 55 | 56 | # The master toctree document. 57 | master_doc = 'index' 58 | 59 | # The language for content autogenerated by Sphinx. Refer to documentation 60 | # for a list of supported languages. 61 | # 62 | # This is also used if you do content translation via gettext catalogs. 63 | # Usually you set "language" from the command line for these cases. 64 | language = None 65 | 66 | # List of patterns, relative to source directory, that match files and 67 | # directories to ignore when looking for source files. 68 | # This pattern also affects html_static_path and html_extra_path. 69 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 70 | 71 | # The name of the Pygments (syntax highlighting) style to use. 72 | pygments_style = None 73 | 74 | 75 | # -- Options for HTML output ------------------------------------------------- 76 | 77 | # The theme to use for HTML and HTML Help pages. See the documentation for 78 | # a list of builtin themes. 79 | # 80 | html_theme = 'alabaster' 81 | 82 | # Theme options are theme-specific and customize the look and feel of a theme 83 | # further. For a list of options available for each theme, see the 84 | # documentation. 85 | # 86 | # html_theme_options = {} 87 | 88 | # Add any paths that contain custom static files (such as style sheets) here, 89 | # relative to this directory. They are copied after the builtin static files, 90 | # so a file named "default.css" will overwrite the builtin "default.css". 91 | html_static_path = ['_static'] 92 | 93 | # Custom sidebar templates, must be a dictionary that maps document names 94 | # to template names. 95 | # 96 | # The default sidebars (for documents that don't match any pattern) are 97 | # defined by theme itself. Builtin themes are using these templates by 98 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', 99 | # 'searchbox.html']``. 100 | # 101 | # html_sidebars = {} 102 | 103 | 104 | # -- Options for HTMLHelp output --------------------------------------------- 105 | 106 | # Output file base name for HTML help builder. 107 | htmlhelp_basename = 'nicewindoc' 108 | 109 | 110 | # -- Options for LaTeX output ------------------------------------------------ 111 | 112 | latex_elements = { 113 | # The paper size ('letterpaper' or 'a4paper'). 114 | # 115 | # 'papersize': 'letterpaper', 116 | 117 | # The font size ('10pt', '11pt' or '12pt'). 118 | # 119 | # 'pointsize': '10pt', 120 | 121 | # Additional stuff for the LaTeX preamble. 122 | # 123 | # 'preamble': '', 124 | 125 | # Latex figure (float) alignment 126 | # 127 | # 'figure_align': 'htbp', 128 | } 129 | 130 | # Grouping the document tree into LaTeX files. List of tuples 131 | # (source start file, target name, title, 132 | # author, documentclass [howto, manual, or own class]). 133 | latex_documents = [ 134 | (master_doc, 'nicewin.tex', 'Nice Win Documentation', 135 | 'Al Sweigart', 'manual'), 136 | ] 137 | 138 | 139 | # -- Options for manual page output ------------------------------------------ 140 | 141 | # One entry per manual page. List of tuples 142 | # (source start file, name, description, authors, manual section). 143 | man_pages = [ 144 | (master_doc, 'nicewin', 'Nice Win Documentation', 145 | [author], 1) 146 | ] 147 | 148 | 149 | # -- Options for Texinfo output ---------------------------------------------- 150 | 151 | # Grouping the document tree into Texinfo files. List of tuples 152 | # (source start file, target name, title, author, 153 | # dir menu entry, description, category) 154 | texinfo_documents = [ 155 | (master_doc, 'nicewin', 'Nice Win Documentation', 156 | author, 'Nice Win', 'A nicely-documented, pure-Python wrapper for the Windows API for Python 2 and 3.', 157 | 'Miscellaneous'), 158 | ] 159 | 160 | 161 | # -- Options for Epub output ------------------------------------------------- 162 | 163 | # Bibliographic Dublin Core info. 164 | epub_title = project 165 | 166 | # The unique identifier of the text. This can be a ISBN number 167 | # or the project homepage. 168 | # 169 | # epub_identifier = '' 170 | 171 | # A unique identification for the text. 172 | # 173 | # epub_uid = '' 174 | 175 | # A list of files that should not be packed into the epub file. 176 | epub_exclude_files = ['search.html'] 177 | 178 | 179 | # -- Extension configuration ------------------------------------------------- -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. Nice Win documentation master file, created by 2 | sphinx-quickstart on Mon Nov 12 14:17:27 2018. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to Nice Win's documentation! 7 | ======================================= 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | :caption: Contents: 12 | 13 | 14 | 15 | Indices and tables 16 | ================== 17 | 18 | * :ref:`genindex` 19 | * :ref:`modindex` 20 | * :ref:`search` 21 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asweigart/nicewin/67cea8cf01797f12ae7399c526105f46659248f2/pyproject.toml -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import re 2 | from setuptools import setup, find_packages 3 | 4 | # Load version from module (without loading the whole module) 5 | with open('src/nicewin/__init__.py', 'r') as fo: 6 | version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', 7 | fo.read(), re.MULTILINE).group(1) 8 | 9 | # Read in the README.md for the long description. 10 | with open('README.md') as fo: 11 | long_description = fo.read() 12 | 13 | setup( 14 | name='Nice Win', 15 | version=version, 16 | url='https://github.com/asweigart/nicewin', 17 | author='Al Sweigart', 18 | author_email='al@inventwithpython.com', 19 | description=('''A nicely-documented, pure-Python wrapper for the Windows API for Python 2 and 3.'''), 20 | long_description=long_description, 21 | long_description_content_type="text/markdown", 22 | license='GPLv3+', 23 | packages=find_packages(where='src'), 24 | package_dir={'': 'src'}, 25 | test_suite='tests', 26 | install_requires=[], 27 | keywords='', 28 | classifiers=[ 29 | 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 30 | 'Programming Language :: Python', 31 | 'Programming Language :: Python :: 3', 32 | 'Programming Language :: Python :: 3.4', 33 | 'Programming Language :: Python :: 3.5', 34 | 'Programming Language :: Python :: 3.6', 35 | 'Programming Language :: Python :: 3.7' 36 | ], 37 | ) 38 | -------------------------------------------------------------------------------- /src/nicewin/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | NiceWin, a nicely-documented wrapper for several Windows API function calls. 3 | By Al Sweigart al@inventwithpython.com 4 | 5 | The primary aim of this module is more for educational purposes than practical 6 | use. I'd recommend the venerable pywin32 module for Windows-related function 7 | calling in your Python code. Please do examine the docstrings for these 8 | functions. 9 | 10 | This module is meant to make it easy to copy/paste example code into your own 11 | programs as well. 12 | 13 | If there are parts of this code that you don't understand, please contact 14 | Al at al@inventwithpython.com with suggestions for what needs to be clarified. 15 | 16 | NOTE: Al Sweigart is not a win32 or Windows system internals expert. 17 | 18 | The best guides to learning to program Windows applications is Charles Petzold's 19 | "Programming Windows" books, currently in its sixth edition, and the "Windows 20 | Internals" books (Part 1 and Part2) by Yosifovich, Russinovich, Solomon, & 21 | Ionescu. 22 | 23 | Microsoft has great documentation on their Docs site (formerly known as MDN, 24 | Microsoft Developer's Network) at 25 | https://docs.microsoft.com/en-us/windows/desktop/api/index 26 | 27 | But usually it's just easiest to google for the particular function you are 28 | looking up. 29 | 30 | Some things to note first about the Windows API: 31 | 32 | * Function names in the Windows API are capitalized, like GetWindowText(). 33 | Their Python equivalents will be written in snake_case. 34 | * hWnd is a "window handle", which you can get from GetForegroundWindow() 35 | and other such functions. An hWnd as an integer that identifies a window. 36 | * Many Windows API functions return an error code, and the actual output 37 | of the function is in a by-reference argument that was passed in. 38 | * The returned error code only indicates an error happened. Call 39 | GetLastError() to get the integer error code and FormatMessage() to 40 | get the error message for that code. 41 | * Many Windows API functions have am A and W suffix: The A is for versions 42 | that use Ansi (Ascii) text, while W is for "wide" (unicode) text. This 43 | module will use the W functions over the A functions. 44 | * TODO - note about dealing with strings and allocating/freeing memory 45 | for them. 46 | 47 | 48 | Note for developers and contributors: 49 | 50 | The primary reason for this module is to ease Python programmers into the 51 | win32 api. As such, if you'd like to contribute, please make note of the 52 | following: 53 | 54 | * The main functions should reflect the win32 function names, even if it 55 | doesn't quite make sense. For example, the LockSetForegroundWindow() 56 | function can both lock and unlock the ability to set the window to the 57 | foreground, but nevertheless we'll name the function 58 | lock_set_foreground_window() in NiceWin. 59 | * However, the arguments and return values can be Pythonic and don't have to 60 | match the win32 API exactly. 61 | * Documentation is important! Follow the docstring format used by 62 | functions in this module; include links to the Microsoft documentation 63 | or Stack Overflow links that explain concepts. Assume the users have 64 | no knowledge of Windows internals concepts. 65 | * In general, we use the W functions, not the A functions. For example, 66 | message_box() calls MessageBoxW(), not MessageBoxA() or MessageBox(). 67 | """ 68 | 69 | __version__ = '0.0.1' 70 | 71 | import ctypes 72 | from ctypes import wintypes # We can't use ctypes.wintypes, we must import wintypes this way. 73 | 74 | from .constants import NULL, SW_FORCEMINIMIZE, SW_HIDE, SW_RESTORE, SW_SHOW, SW_SHOWMAXIMIZED, SW_SHOWMINIMIZED, FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_ALLOCATE_BUFFER, FORMAT_MESSAGE_IGNORE_INSERTS, AW_ACTIVATE, AW_HIDE, LSFW_LOCK, LSFW_UNLOCK, MB_OKCANCEL, IDABORT, IDCANCEL, IDCONTINUE, IDIGNORE, IDNO, IDOK, IDRETRY, IDTRYAGAIN, IDYES, HWND_TOP, MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTONULL, MONITOR_DEFAULTTOPRIMARY 75 | 76 | 77 | from .structs import POINT, RECT, WINDOWPLACEMENT 78 | 79 | import collections 80 | 81 | 82 | # NOTE: `Rect` is a named tuple for use in Python, while structs.RECT represents 83 | # the win32 RECT struct. 84 | Rect = collections.namedtuple('Rect', 'left top right bottom') 85 | 86 | class NiceWinException(Exception): 87 | """This class exists for any exceptions raised by the nicewin module. If 88 | nicewin raises any other exceptions, assume that that is a bug in this 89 | module.""" 90 | pass 91 | 92 | 93 | def _raiseWithLastError(): 94 | """A helper function that raises NiceWinException using the error 95 | information from GetLastError() and FormatMessage().""" 96 | errorCode = ctypes.windll.kernel32.GetLastError() 97 | raise NiceWinException('Error code from Windows: %s - %s' % (errorCode, format_message(errorCode))) 98 | 99 | 100 | class Window: 101 | """A class that represents a Window, to provide a richer representation 102 | than just a `hWnd` "window handle". 103 | 104 | Window handles are recycled, so the particular hWnd value could later be 105 | used for a different window. 106 | 107 | TODO 108 | """ 109 | def __init__(self, hWnd): 110 | """Create a Window object given an `hWnd` "window handle". TODO""" 111 | if not hWnd: 112 | raise NiceWinException('hWnd arg must be a nonzero integer') 113 | 114 | self.hWnd = hWnd 115 | 116 | 117 | def __str__(self): 118 | r = get_window_text(self) 119 | width = r.right - r.left 120 | height = r.bottom - r.top 121 | return '<%s left="%s", top="%s", width="%s", height="%s", title="%s">' % (self.__class__.__name__, r.left, r.top, width, height, self.title) 122 | 123 | 124 | def __repr__(self): 125 | return '%s(hWnd=%s)' % (self.__class__.__name__, self.hWnd) 126 | 127 | 128 | def __eq__(self, other): 129 | return isinstance(other, Window) and other.hWnd == self.hWnd 130 | 131 | 132 | @property 133 | def title(self): 134 | """The string of the title or caption in the top bar of the window.""" 135 | return get_window_text(self) 136 | 137 | @title.setter 138 | def title(self, value): 139 | set_window_text(self, str(value)) 140 | 141 | 142 | @property 143 | def width(self): 144 | r = get_window_rect(self) 145 | return r.right - r.left 146 | 147 | @property 148 | def height(self): 149 | r = get_window_rect(self) 150 | return r.bottom - r.top 151 | 152 | @property 153 | def size(self): 154 | r = get_window_rect(self) 155 | return (r.right - r.left, r.bottom - r.top) 156 | 157 | @property 158 | def topleft(self): 159 | r = get_window_rect(self) 160 | return (r.left, r.top) 161 | 162 | @property 163 | def topright(self): 164 | r = get_window_rect(self) 165 | return (r.right, r.top) 166 | 167 | @property 168 | def bottomleft(self): 169 | r = get_window_rect(self) 170 | return (r.left, r.bottom) 171 | 172 | @property 173 | def bottomright(self): 174 | r = get_window_rect(self) 175 | return (r.right, r.bottom) 176 | 177 | @property 178 | def top(self): 179 | return get_window_rect(self).top 180 | 181 | @property 182 | def bottom(self): 183 | return get_window_rect(self).bottom 184 | 185 | @property 186 | def left(self): 187 | return get_window_rect(self).left 188 | 189 | @property 190 | def right(self): 191 | return get_window_rect(self).right 192 | 193 | 194 | @property 195 | def visible(self): 196 | """A bool for of the window is visible (shown) or not (hidden).""" 197 | return is_window_visible(self) 198 | 199 | @visible.setter 200 | def visible(self, value): 201 | if value: 202 | self.show() 203 | else: 204 | self.hide() 205 | 206 | 207 | @property 208 | def maximized(self): 209 | """A bool for if the window is maximized or not.""" 210 | return is_zoomed(self) 211 | 212 | @maximized.setter 213 | def maximized(self, value): 214 | if value: 215 | self.maximize() 216 | else: 217 | if is_zoomed(self): 218 | # Already maximized, so restore the window. 219 | self.restore() 220 | else: 221 | # Not maximized, so do nothing. 222 | pass 223 | 224 | 225 | @property 226 | def minimized(self): 227 | """A bool for if the window is minimized or not.""" 228 | return is_iconic(self) 229 | 230 | @minimized.setter 231 | def minimized(self, value): 232 | if value: 233 | self.minimize() 234 | else: 235 | if is_iconic(self): 236 | # Already minimized, so restore the window. 237 | open_icon(self) 238 | else: 239 | # Not minimized, so do nothing. 240 | pass 241 | 242 | 243 | # ShowWindow() methods: 244 | def hide(self): 245 | """Hide the window by making it invisible. Hiding is different from 246 | minimizing. It'll only reappear when `show()` is called on it. 247 | 248 | Returns either 'window was previously hidden' or 249 | 'window was previously visible'. 250 | """ 251 | return show_window(self, SW_HIDE) 252 | 253 | 254 | def show(self): 255 | """Show the window by making it visible. 256 | 257 | Returns either 'window was previously hidden' or 258 | 'window was previously visible'. 259 | """ 260 | return show_window(self, SW_SHOW) 261 | 262 | 263 | def force_minimize(self): 264 | """Minimizes this window to the taskbar, even if the thread is busy 265 | running other code. 266 | 267 | Returns either 'window was previously hidden' or 268 | 'window was previously visible'. 269 | """ 270 | return show_window(self, SW_FORCEMINIMIZE) 271 | 272 | 273 | def maximize(self): 274 | """Maximizes this window to fill the screen. 275 | 276 | Returns either 'window was previously hidden' or 277 | 'window was previously visible'. 278 | """ 279 | show_window(self, SW_SHOWMAXIMIZED) 280 | 281 | 282 | def minimize(self): 283 | """Minimize this window to the taskbar. 284 | 285 | Returns either 'window was previously hidden' or 286 | 'window was previously visible'. 287 | """ 288 | show_window(self, SW_SHOWMINIMIZED) 289 | 290 | 291 | def restore(self): 292 | """Restores this window from the minimized or maximized state. 293 | 294 | Returns either 'window was previously hidden' or 295 | 'window was previously visible'. 296 | """ 297 | show_window(self, SW_RESTORE) 298 | 299 | 300 | def bring_to_top(self): 301 | """Moves this window to the top of the z-order in front of other 302 | windows. 303 | 304 | Returns either 'window was previously hidden' or 305 | 'window was previously visible'. 306 | """ 307 | bring_window_to_top(self) 308 | 309 | 310 | 311 | def animate_window(window_obj, milliseconds, animationType): 312 | """A nice wrapper for AnimateWindow(). Allows you to animate a window while 313 | showing or hiding it. There are four types of animation: roll, slide, 314 | collapse or expand, and alpha-blended fade. 315 | 316 | Syntax: 317 | BOOL AnimateWindow( 318 | HWND hWnd, 319 | DWORD dwTime, 320 | DWORD dwFlags 321 | ); 322 | 323 | Microsoft Documentation: 324 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-animatewindow 325 | """ 326 | if (animationType & AW_ACTIVATE != 0) and (animationType & AW_HIDE != 0): 327 | raise NiceWinException('animationType can\'t be both AW_ACTIVATE and AW_HIDE') 328 | 329 | ctypes.windll.user32.AnimateWindow(window_obj.hWnd, milliseconds, animationType) 330 | 331 | 332 | 333 | def bring_window_to_top(window_obj): 334 | """A nice wrapper for BringWindowToTop(). Brings the window to the top of 335 | the z-order, on top of all other windows. 336 | 337 | Additional info: 338 | https://stackoverflow.com/questions/1544179/what-are-the-differences-between-bringwindowtotop-setforegroundwindow-setwindo 339 | 340 | TODO NOTE: This doesn't actually seem to work. You might want to try 341 | set_foreground_window() instead. I'm not sure what the difference is. 342 | 343 | Syntax: 344 | BOOL BringWindowToTop( 345 | HWND hWnd 346 | ); 347 | 348 | Microsoft Documentation: 349 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-bringwindowtotop 350 | """ 351 | result = ctypes.windll.user32.BringWindowToTop(window_obj.hWnd) 352 | if result == 0: 353 | _raiseWithLastError() 354 | 355 | 356 | def clip_cursor(left=None, top=None, right=None, bottom=None): 357 | """A nice wrapper for ClipCursor(). Restricts the mouse cursor to the are 358 | on the screen dictated by `left`, `top`, `right`, and `bottom`. 359 | 360 | If no arguments are passed, the cursor is free to move anywhere. 361 | 362 | Syntax: 363 | BOOL ClipCursor( 364 | const RECT *lpRect 365 | ); 366 | 367 | Microsoft Documentation: 368 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-clipcursor 369 | 370 | An example of confining a cursor: 371 | https://docs.microsoft.com/en-us/windows/desktop/menurc/using-cursors#confining-a-cursor 372 | """ 373 | if (left is None) or (top is None) or (right is None) or (bottom is None): 374 | if (left is None) and (top is None) and (right is None) and (bottom is None): 375 | # Call ClipCursor() and pass NULL. 376 | result = ctypes.windll.user32.ClipCursor(NULL) 377 | else: 378 | # One of the parameters is None, but not all of them. 379 | raise NiceWinException('either all args must be None or none of the args can be None') 380 | else: 381 | # All of the args have been specified. 382 | rect = RECT() 383 | rect.left = left 384 | rect.top = top 385 | rect.right = right 386 | rect.bottom = bottom 387 | result = ctypes.windll.user32.ClipCursor(rect) # TODO i dont' think I'm passing this correctly. 388 | 389 | if result != 0: 390 | return True 391 | else: 392 | _raiseWithLastError() 393 | 394 | 395 | 396 | def close_window(window_obj): 397 | """A nice wrapper for CloseWindow(). Activates (puts in focus) the window 398 | and minimizes it, if it is not already minimized. This function is poorly 399 | named: it doesn't "destroy" the window. 400 | 401 | According to https://stackoverflow.com/a/4904953/1893164, CloseWindow() 402 | is just an older function like IsIconic() and IsZoomed(). It is extended 403 | by ShowWindow(). 404 | 405 | 406 | 407 | Syntax: 408 | BOOL CloseWindow(HWND hWnd); 409 | 410 | Additional Information: 411 | https://stackoverflow.com/questions/4904757/closewindow-vs-showwindowhwnd-sw-minimize 412 | 413 | Microsoft Documentation: 414 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-closewindow 415 | """ 416 | result = ctypes.windll.user32.CloseWindow(window_obj.hWnd) 417 | if result == 0: 418 | _raiseWithLastError() 419 | 420 | 421 | def destroy_window(window_obj): 422 | """A nice wrapper for DestroyWindow(). 423 | 424 | This can only close a window created by the same thread running this code. 425 | If you want to close a different window, call PostMessageA() and pass the 426 | WM_CLOSE message. 427 | 428 | Syntax: 429 | BOOL DestroyWindow(HWND hWnd); 430 | 431 | Microsoft Documentation: 432 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-destroywindow 433 | """ 434 | result = ctypes.windll.user32.DestroyWindow(window_obj.hWnd) 435 | if result == NULL: 436 | _raiseWithLastError() 437 | 438 | 439 | def find_window(windowName): 440 | """A nice wrapper for FindWindowW(). TODO 441 | 442 | Syntax: 443 | HWND FindWindowW( 444 | LPCWSTR lpClassName, 445 | LPCWSTR lpWindowName 446 | ); 447 | 448 | Microsoft Documentation: 449 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-findwindoww 450 | 451 | Additional information about Window Classes: 452 | https://docs.microsoft.com/en-us/windows/desktop/winmsg/window-classes 453 | """ 454 | hWnd = ctypes.windll.user32.FindWindowW(NULL, windowName) 455 | if hWnd == NULL: 456 | _raiseWithLastError() 457 | else: 458 | return Window(hWnd) 459 | 460 | 461 | def format_message(errorCode): 462 | """A nice wrapper for FormatMessageW(). TODO 463 | 464 | Syntax: 465 | DWORD FormatMessage( 466 | DWORD dwFlags, 467 | LPCVOID lpSource, 468 | DWORD dwMessageId, 469 | DWORD dwLanguageId, 470 | LPTSTR lpBuffer, 471 | DWORD nSize, 472 | va_list *Arguments 473 | ); 474 | 475 | Microsoft Documentation: 476 | https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-formatmessagew 477 | 478 | Additional information: 479 | https://stackoverflow.com/questions/18905702/python-ctypes-and-mutable-buffers 480 | https://stackoverflow.com/questions/455434/how-should-i-use-formatmessage-properly-in-c 481 | """ 482 | lpBuffer = wintypes.LPWSTR() 483 | 484 | ctypes.windll.kernel32.FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, 485 | NULL, 486 | errorCode, 487 | 0, # dwLanguageId 488 | ctypes.cast(ctypes.byref(lpBuffer), wintypes.LPWSTR), 489 | 0, # nSize 490 | NULL) 491 | msg = lpBuffer.value.rstrip() 492 | ctypes.windll.kernel32.LocalFree(lpBuffer) # Free the memory allocated for the error message's buffer. 493 | return msg 494 | 495 | 496 | def get_active_window(): 497 | """A nice wrapper for GetActiveWindow(). 498 | 499 | Syntax: 500 | HWND GetActiveWindow(); 501 | 502 | According to https://stackoverflow.com/questions/3940346/foreground-vs-active-window 503 | the "active window" is the window attached to the thread calling this 504 | function, while the "foreground window" is the window that is currently 505 | getting input. 506 | 507 | Microsoft Documentation: 508 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getactivewindow 509 | """ 510 | hWnd = ctypes.windll.user32.GetActiveWindow() 511 | if hWnd == 0: 512 | return None # Note that this function doesn't use GetLastError(). 513 | else: 514 | return Window(hWnd) 515 | 516 | 517 | def get_client_rect(window_obj): 518 | """A nice wrapper for GetClientRect(). TODO 519 | 520 | Syntax: 521 | BOOL GetClientRect( 522 | HWND hWnd, 523 | LPRECT lpRect 524 | ); 525 | 526 | Microsoft Documentation: 527 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getclientrect 528 | 529 | Additional documentation about RECT structures: 530 | https://msdn.microsoft.com/en-us/library/windows/desktop/dd162897(v=vs.85).aspx 531 | """ 532 | rect = RECT() 533 | result = ctypes.windll.user32.GetClientRect(window_obj.hWnd, ctypes.byref(rect)) 534 | if result == 0: 535 | _raiseWithLastError() 536 | else: 537 | return (rect.left, rect.top, rect.right, rect.bottom) 538 | 539 | 540 | def get_cursor_pos(): 541 | """A nice wrapper for GetCursorPos(). This returns an (x, y) tuple of the 542 | mouse cursor's position, in screen coordinates. 543 | 544 | Syntax: 545 | BOOL GetCursorPos( 546 | LPPOINT lpPoint 547 | ); 548 | 549 | Microsoft Documentation: 550 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getcursorpos 551 | """ 552 | 553 | cursor = POINT() 554 | ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor)) 555 | return (cursor.x, cursor.y) 556 | 557 | 558 | def get_cursor(): 559 | """A nice wrapper for GetCursor(). TODO 560 | 561 | Syntax: 562 | HCURSOR GetCursor(); 563 | 564 | Microsoft Documentation: 565 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getcursor 566 | """ 567 | pass # TODO 568 | 569 | 570 | def get_cursor_info(): 571 | """A nice wrapper for GetCursorInfo(). TODO 572 | 573 | Syntax: 574 | BOOL GetCursorInfo( 575 | PCURSORINFO pci 576 | ); 577 | 578 | Microsoft Documentation: 579 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getcursorinfo 580 | """ 581 | pass # TODO 582 | 583 | 584 | def get_desktop_window(): 585 | """A nice wrapper for GetDesktopWindow(). TODO 586 | 587 | Syntax: 588 | HWND GetDesktopWindow(); 589 | 590 | Microsoft Documentation: 591 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getdesktopwindow 592 | """ 593 | return Window(ctypes.windll.user32.GetDesktopWindow()) 594 | 595 | 596 | def get_drives(): 597 | """A nice wrapper for _getdrives(). TODO 598 | 599 | Syntax: 600 | unsigned long _getdrives( void ); 601 | 602 | Microsoft Documentation: 603 | https://msdn.microsoft.com/en-us/library/xdhk0xd2.aspx 604 | """ 605 | available_drives = [] 606 | available_drive_flags = ctypes.cdll.msvcrt._getdrives() 607 | for flag in range(26): 608 | if available_drive_flags & (1 << flag): 609 | available_drives.append('ABCDEFGHIJKLMNOPQRSTUVWXYZ'[flag]) 610 | return available_drives 611 | 612 | 613 | def get_foreground_window(): 614 | """A nice wrapper for GetForegroundWindow(). 615 | 616 | Syntax: 617 | HWND GetForegroundWindow(); 618 | 619 | According to https://stackoverflow.com/questions/3940346/foreground-vs-active-window 620 | the "active window" is the window attached to the thread calling this 621 | function, while the "foreground window" is the window that is currently 622 | getting input. 623 | 624 | Microsoft Documentation: 625 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getforegroundwindow 626 | """ 627 | # https://stackoverflow.com/questions/3940346/foreground-vs-active-window 628 | hWnd = ctypes.windll.user32.GetForegroundWindow() 629 | if hWnd == 0: 630 | return None # Note that this function doesn't use GetLastError(). 631 | else: 632 | return Window(hWnd) 633 | 634 | 635 | def get_last_error(): 636 | """A nice wrapper for GetLastError(). When Windows API function call fail, 637 | they usually only indicate that an error happened, not what the actual 638 | error was. It is convention to call GetLastError() to get the actual error 639 | code, and then FormatMessage() to get the error message based on this code. 640 | 641 | Syntax: 642 | DWORD GetLastError(); 643 | 644 | Microsoft Documentation: 645 | https://msdn.microsoft.com/en-us/d852e148-985c-416f-a5a7-27b6914b45d4 646 | """ 647 | return ctypes.windll.kernel32.GetLastError() 648 | 649 | 650 | def get_user_name(): 651 | """TODO 652 | 653 | TODO - This currently doesn't work and returns a blank string. 654 | """ 655 | # Copied from https://sjohannes.wordpress.com/2010/06/19/win32-python-getting-users-display-name-using-ctypes/ 656 | GetUserNameEx = ctypes.windll.secur32.GetUserNameExW 657 | NameDisplay = 3 658 | 659 | size = ctypes.pointer(ctypes.c_ulong(0)) 660 | GetUserNameEx(NameDisplay, None, size) 661 | 662 | nameBuffer = ctypes.create_unicode_buffer(size.contents.value) 663 | GetUserNameEx(NameDisplay, nameBuffer, size) 664 | return nameBuffer.value 665 | 666 | 667 | def get_window(window_obj, relationship): 668 | """A nice wrapper for GetWindow(). TODO 669 | 670 | Syntax: 671 | HWND GetWindow( 672 | HWND hWnd, 673 | UINT uCmd 674 | ); 675 | 676 | Microsoft Documentation: 677 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindow 678 | """ 679 | hWnd = ctypes.windll.user32.GetWindow(window_obj.hWnd, relationship) 680 | if hWnd == NULL: 681 | _raiseWithLastError() 682 | else: 683 | return Window(hWnd) 684 | 685 | 686 | def get_window_placement(window_obj): 687 | """A nice wrapper for GetWindowPlacement(). TODO 688 | 689 | "Retrieves the show state and the restored, minimized, and maximized positions of the specified window." 690 | 691 | Syntax: 692 | BOOL GetWindowPlacement( 693 | HWND hWnd, 694 | WINDOWPLACEMENT *lpwndpl 695 | ); 696 | 697 | Microsoft Documention: 698 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowplacement 699 | 700 | Additional documentation for WINDOWPLACEMENT: 701 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagwindowplacement 702 | """ 703 | windowPlacement = WINDOWPLACEMENT 704 | result = ctypes.windll.user32.GetWindowPlacement(window_obj.hWnd, ctypes.byref(windowPlacement)) 705 | if result == 0: 706 | _raiseWithLastError() 707 | else: 708 | return windowPlacement # TODO - finish this 709 | 710 | 711 | def get_window_rect(window_obj): 712 | """A nice wrapper for GetWindowRect(). TODO 713 | 714 | Syntax: 715 | BOOL GetWindowRect( 716 | HWND hWnd, 717 | LPRECT lpRect 718 | ); 719 | 720 | Microsoft Documentation: 721 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowrect 722 | """ 723 | rect = RECT() 724 | result = ctypes.windll.user32.GetWindowRect(window_obj.hWnd, ctypes.byref(rect)) 725 | if result != 0: 726 | return Rect(rect.left, rect.top, rect.right, rect.bottom) 727 | else: 728 | _raiseWithLastError() 729 | 730 | 731 | def get_window_text(window_obj): 732 | """A nice wrapper for GetWindowTextW(). TODO 733 | 734 | Syntax: 735 | int GetWindowTextW( 736 | HWND hWnd, 737 | LPWSTR lpString, 738 | int nMaxCount 739 | ); 740 | 741 | int GetWindowTextLengthW( 742 | HWND hWnd 743 | ); 744 | 745 | Microsoft Documentation: 746 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowtextw 747 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowtextlengthw 748 | """ 749 | textLenInCharacters = ctypes.windll.user32.GetWindowTextLengthW(window_obj.hWnd) 750 | stringBuffer = ctypes.create_unicode_buffer(textLenInCharacters + 1) # +1 for the \0 at the end of the null-terminated string. 751 | ctypes.windll.user32.GetWindowTextW(window_obj.hWnd, stringBuffer, textLenInCharacters + 1) 752 | 753 | # TODO it's ambiguous if an error happened or the title text is just empty. Look into this later. 754 | return stringBuffer.value 755 | 756 | 757 | def get_window_thread_process_id(window_obj): 758 | """A nice wrapper for GetWindowThreadProcessId(). Returns a tuple of the 759 | thread id (tid) of the thread that created the specified window, and the 760 | process id that created the window. 761 | 762 | Syntax: 763 | DWORD GetWindowThreadProcessId( 764 | HWND hWnd, 765 | LPDWORD lpdwProcessId 766 | ); 767 | 768 | Microsoft Documentation: 769 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindowthreadprocessid 770 | """ 771 | pid = wintypes.DWORD() 772 | tid = ctypes.windll.user32.GetWindowThreadProcessId(window_obj.hWnd, ctypes.byref(pid)) 773 | return tid, pid.value 774 | 775 | 776 | def is_child(parent_window_obj, child_window_obj): 777 | """A nice wrapper for IsChild(). Returns `True` if `child_window_obj` is a 778 | child window of `parent_window_obj`. 779 | 780 | Syntax: 781 | BOOL IsChild( 782 | HWND hWndParent, 783 | HWND hWnd 784 | ); 785 | 786 | Microsoft Documentation: 787 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-ischild 788 | """ 789 | return ctypes.windll.user32.IsChild(parent_window_obj.hWnd, child_window_obj.hWnd) != 0 790 | 791 | 792 | def is_gui_thread(convert_to_gui=False): 793 | """A nice wrapper for IsGuiThread(). If `convert_to_gui` is `True`, then 794 | the thread will be converted to one. 795 | 796 | TODO - write more about gui threads 797 | 798 | Syntax: 799 | BOOL IsGUIThread( 800 | BOOL bConvert 801 | ); 802 | 803 | Microsoft Documentation: 804 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-isguithread 805 | 806 | TODO - handle ERROR_NOT_ENOUGH_MEMORY case 807 | """ 808 | return ctypes.windll.user32.IsGuiThread(convert_to_gui) != 0 809 | 810 | 811 | def is_iconic(window_obj): 812 | """A nice wrapper for IsIconic(). Returns `True` if `window_obj` is 813 | "iconic", that is, minimized. 814 | 815 | According to https://stackoverflow.com/a/4904953/1893164, IsIconic() 816 | is just an older function like CloseWindow() and IsZoomed(). It is extended 817 | by ShowWindow(). 818 | 819 | Syntax: 820 | BOOL IsIconic( 821 | HWND hWnd 822 | ); 823 | 824 | Microsoft Documentation: 825 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-isiconic 826 | """ 827 | return ctypes.windll.user32.IsIconic(window_obj.hWnd) != 0 828 | 829 | 830 | def is_process_dpi_aware(): 831 | """A nice wrapper for IsProcessDPIAware(). TODO 832 | 833 | Syntax: 834 | BOOL IsProcessDPIAware(); 835 | 836 | Microsoft Documentation: 837 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-isprocessdpiaware 838 | """ 839 | return bool(ctypes.windll.user32.IsProcessDPIAware()); 840 | 841 | 842 | def is_window(window_obj): 843 | """A nice wrapper for IsWindow(). Returns `True` if `window_obj` identifies 844 | an existing window. 845 | 846 | A thread shouldn't call is_window() on a window that it didn't create 847 | because it could later be destroyed, making the return value out of date. 848 | 849 | Window handles are recycled, so the particular hWnd value could later be 850 | used for a different window. 851 | 852 | Syntax: 853 | BOOL IsWindow( 854 | HWND hWnd 855 | ); 856 | 857 | Microsoft Documentation: 858 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-iswindow 859 | """ 860 | return ctypes.windll.user32.IsWindow(window_obj.hWnd) != 0 861 | 862 | 863 | def is_window_unicode(window_obj): 864 | """A nice wrapper for IsWindowUnicode(). Returns `True` if the specified 865 | window is a native Unicode window. The character set of a window is 866 | determined by the window class that was registered (through 867 | RegisterClass()). 868 | 869 | Syntax: 870 | BOOL IsWindowUnicode( 871 | HWND hWnd 872 | ); 873 | 874 | Microsoft Documentation: 875 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-iswindowunicode 876 | """ 877 | return ctypes.windll.user32.IsWindowUnicode(window_obj.hWnd) != 0 878 | 879 | 880 | def is_window_visible(window_obj): 881 | """A nice wrapper for IsWindowVisible(). TODO 882 | 883 | Syntax: 884 | BOOL IsWindowVisible( 885 | HWND hWnd 886 | ); 887 | 888 | Microsoft Documentation: 889 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-iswindowvisible 890 | 891 | WS_VISIBLE discussed in: 892 | https://docs.microsoft.com/en-us/windows/desktop/winmsg/window-styles 893 | """ 894 | return ctypes.windll.user32.IsWindowVisible(window_obj.hWnd) != 0 895 | 896 | 897 | def is_zoomed(window_obj): 898 | """A nice wrapper for IsZoomed(). Returns `True` if the specified window 899 | is "zoomed", that is, maximized. 900 | 901 | According to https://stackoverflow.com/a/4904953/1893164, IsZoomed() 902 | is just an older function like IsIconic() and CloseWindow(). It is extended 903 | by ShowWindow(). 904 | 905 | Syntax: 906 | BOOL IsZoomed( 907 | HWND hWnd 908 | ); 909 | 910 | Microsoft Documentation: 911 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-iszoomed 912 | """ 913 | return ctypes.windll.user32.IsZoomed(window_obj.hWnd) != 0 914 | 915 | 916 | def lock_set_foreground_window(lock=True): 917 | """A nice wrapper for LockSetForegroundWindow(). By passing `LSFW_LOCK` for 918 | `lock`, you can disable calls to the SetForegroundWindow() function. 919 | 920 | Syntax: 921 | BOOL LockSetForegroundWindow( 922 | UINT uLockCode 923 | ); 924 | 925 | Microsoft Documentation: 926 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-locksetforegroundwindow 927 | """ 928 | result = ctypes.windll.user32.LocSetForegroundWindow(LSFW_LOCK if lock else LSFW_UNLOCK) 929 | if result == 0: 930 | _raiseWithLastError() 931 | else: 932 | return True 933 | 934 | 935 | def logical_to_physical_point(window_obj, logical_x, logical_y): 936 | """A nice wrapper for LogicalToPhysicalPoint(). A tuple of (x, y) physical 937 | point coordinates is returned matching the logical point in `window_obj`. 938 | 939 | TODO - I don't think this function works. It keeps returning 0, 0. 940 | 941 | Syntax: 942 | BOOL LogicalToPhysicalPoint( 943 | HWND hWnd, 944 | LPPOINT lpPoint 945 | ); 946 | 947 | "Currently MessageBoxEx and MessageBox work the same way." 948 | 949 | Microsoft Documentation: 950 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-logicaltophysicalpoint 951 | """ 952 | physicalPoint = POINT() 953 | ctypes.windll.user32.LogicalToPhysicalPoint(window_obj.hWnd, 954 | ctypes.byref(physicalPoint)) 955 | return (physicalPoint.x, physicalPoint.y) 956 | 957 | 958 | def message_box(owner_window_obj, text, caption, box_type=MB_OKCANCEL): 959 | """A nice wrapper for MessageBoxW(). Displays a modal dialog box with a 960 | system icon, set of buttons, and message. Returns an integer that 961 | indicates which button the user clicked. 962 | 963 | Syntax: 964 | int MessageBoxW( 965 | HWND hWnd, 966 | LPCWSTR lpText, 967 | LPCWSTR lpCaption, 968 | UINT uType 969 | ); 970 | 971 | Microsoft Documentation: 972 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-messageboxw 973 | """ 974 | result = ctypes.windll.user32.MessageBoxW(owner_window_obj.hWnd, 975 | text, 976 | caption, 977 | box_type) 978 | if result == 0: 979 | _raiseWithLastError() 980 | else: 981 | return {IDABORT: 'abort', 982 | IDCANCEL: 'cancel', 983 | IDCONTINUE: 'continue', 984 | IDIGNORE: 'ignore', 985 | IDNO: 'no', 986 | IDOK: 'ok', 987 | IDRETRY: 'retry', 988 | IDTRYAGAIN: 'try again', 989 | IDYES: 'yes'}[result] 990 | 991 | 992 | def move_window(window_obj, x, y, width, height, repaint=True): 993 | """A nice wrapper for MoveWindow(). The dimensions of the window specified 994 | by `window_obj` are moved and resized so that the topleft corner is at 995 | `x` and `y`, with a size given by `width` and `height`. 996 | 997 | Syntax: 998 | BOOL MoveWindow( 999 | HWND hWnd, 1000 | int X, 1001 | int Y, 1002 | int nWidth, 1003 | int nHeight, 1004 | BOOL bRepaint 1005 | ); 1006 | 1007 | Microsoft Documentation: 1008 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-movewindow 1009 | """ 1010 | result = ctypes.windll.user32.MoveWindow(window_obj.hWnd, x, y, width, height, repaint) 1011 | if result == 0: 1012 | _raiseWithLastError() 1013 | else: 1014 | return True 1015 | 1016 | 1017 | def open_icon(window_obj): 1018 | """A nice wrapper for OpenIcon(). This function restores a minimized, that 1019 | is, iconic, window to its previous size and position. Then it activates, 1020 | that is, focuses, the window. 1021 | 1022 | Syntax: 1023 | BOOL OpenIcon( 1024 | HWND hWnd 1025 | ); 1026 | 1027 | Microsoft Documentation: 1028 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-openicon 1029 | """ 1030 | result = ctypes.windll.user32.OpenIcon(window_obj.hWnd) 1031 | if result == 0: 1032 | _raiseWithLastError() 1033 | else: 1034 | return True 1035 | 1036 | 1037 | def physical_to_logical_point(window_obj, physical_x, physical_y): 1038 | """A nice wrapper for PhysicalToLogicalPoint(). Returns the logical point 1039 | of `physical_x` and `physical_y` in the `window_obj`. 1040 | 1041 | TODO - this doesn't work for now, it always returns (0, 0) 1042 | 1043 | Syntax: 1044 | BOOL PhysicalToLogicalPoint( 1045 | HWND hWnd, 1046 | LPPOINT lpPoint 1047 | ); 1048 | 1049 | Microsoft Documentation: 1050 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-physicaltologicalpoint 1051 | """ 1052 | logicalPoint = POINT() 1053 | ctypes.windll.user32.PhysicalToLogicalPoint(window_obj.hWnd, 1054 | ctypes.byref(logicalPoint)) 1055 | return (logicalPoint.x, logicalPoint.y) 1056 | 1057 | 1058 | 1059 | def peek_message(): 1060 | # TODO 1061 | ctypes.windll.user32.PeekMessage() 1062 | 1063 | 1064 | def set_foreground_window(window_obj): 1065 | """A nice wrapper for SetForegroundWindow(). TODO 1066 | 1067 | Syntax: 1068 | BOOL SetForegroundWindow( 1069 | HWND hWnd 1070 | ); 1071 | 1072 | Microsoft Documentation: 1073 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setforegroundwindow 1074 | """ 1075 | result = ctypes.windll.user32.SetForegroundWindow(window_obj.hWnd) 1076 | if result == 0: # There is no GetLastError() for this function. 1077 | raise NiceWinException('Unable to set this window as the foreground window. For possible causes, see https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setforegroundwindow#remarks') 1078 | 1079 | 1080 | def set_window_pos(window_obj, left, top, width, height, z=HWND_TOP, flags=0): 1081 | """A nice wrapper for SetWindowPos(). While SetWindowPos() is similar to 1082 | MoveWindow(), you can consider it to be a sort of "MoveWindowEx()". 1083 | 1084 | "Changes the size, position, and Z order of a child, pop-up, or top-level window. These windows are ordered according to their appearance on the screen. The topmost window receives the highest rank and is the first window in the Z order." 1085 | Syntax: 1086 | BOOL SetWindowPos( 1087 | HWND hWnd, 1088 | HWND hWndInsertAfter, 1089 | int X, 1090 | int Y, 1091 | int cx, 1092 | int cy, 1093 | UINT uFlags 1094 | ); 1095 | 1096 | Microsot Documentation: 1097 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setwindowpos 1098 | 1099 | https://blogs.msdn.microsoft.com/oldnewthing/20090323-00/?p=18733/ 1100 | """ 1101 | result = ctypes.windll.user32.SetWindowPos(window_obj.hWnd, z, left, top, width, height, flags) 1102 | if result == 0: 1103 | _raiseWithLastError() 1104 | 1105 | 1106 | def set_window_text(window_obj, text): 1107 | """A nice wrapper for SetWindowTextW(). TODO 1108 | 1109 | Syntax: 1110 | BOOL SetWindowTextW( 1111 | HWND hWnd, 1112 | LPCWSTR lpString 1113 | ); 1114 | 1115 | Microsoft Documentation: 1116 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setwindowtextw 1117 | """ 1118 | result = ctypes.windll.user32.SetWindowTextW(window_obj.hWnd, text) 1119 | if result == 0: 1120 | _raiseWithLastError() 1121 | 1122 | 1123 | def show_window(window_obj, action): 1124 | """"A nice wrapper for ShowWindow(). TODO 1125 | 1126 | The `action` arg is one of the following: 1127 | SW_FORCEMINIMIZE, SW_HIDE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOW, 1128 | SW_SHOWDEFAULT, SW_SHOWMAXIMIZED, SW_SHOWMINIMIZED, SW_SHOWMINNOACTIVE, 1129 | SW_SHOWNA, SW_SHOWNOACTIVATE, SW_SHOWNORMAL 1130 | See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-showwindow#parameters 1131 | 1132 | Syntax: 1133 | BOOL ShowWindow( 1134 | HWND hWnd, 1135 | int nCmdShow 1136 | ); 1137 | 1138 | Microsoft Documentation: 1139 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-showwindow 1140 | """ 1141 | 1142 | result = ctypes.windll.user32.ShowWindow(window_obj.hWnd, action) 1143 | 1144 | if result == 0: 1145 | return 'window was previously hidden' 1146 | else: 1147 | return 'window was previously visible' 1148 | 1149 | 1150 | def show_window_async(window_obj, action): 1151 | """A nice wrapper for ShowWindowAsync(). TODO - doesn't wait for action to complete before returning. 1152 | 1153 | The `action` arg is one of the following: 1154 | SW_FORCEMINIMIZE, SW_HIDE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOW, 1155 | SW_SHOWDEFAULT, SW_SHOWMAXIMIZED, SW_SHOWMINIMIZED, SW_SHOWMINNOACTIVE, 1156 | SW_SHOWNA, SW_SHOWNOACTIVATE, SW_SHOWNORMAL 1157 | See https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-showwindow#parameters 1158 | 1159 | Syntax: 1160 | BOOL ShowWindowAsync( 1161 | HWND hWnd, 1162 | int nCmdShow 1163 | ); 1164 | 1165 | Microsoft Documentation: 1166 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-showwindowasync 1167 | """ 1168 | result = ctypes.windll.user32.ShowWindowAsync(window_obj.hWnd, action) 1169 | return result != 0 # Note that this function doesn't use GetLastError(). 1170 | 1171 | 1172 | def wait_message(): 1173 | """A nice wrapper for WaitMessage(). TODO 1174 | 1175 | Syntax: 1176 | BOOL WaitMessage(); 1177 | 1178 | Microsoft Documentation: 1179 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-waitmessage 1180 | """ 1181 | result = ctypes.windll.user32.WaitMessage() 1182 | return result != 0 # Note that this function doesn't use GetLastError(). 1183 | 1184 | 1185 | def window_from_physical_point(x, y): 1186 | """A nice wrapper for WindowFromPhysicalPoint. TODO 1187 | 1188 | Syntax: 1189 | HWND WindowFromPhysicalPoint( 1190 | POINT Point 1191 | ); 1192 | 1193 | Microsoft Documentation: 1194 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-windowfromphysicalpoint 1195 | 1196 | Additional Information: 1197 | https://stackoverflow.com/questions/4324954/whats-the-difference-between-windowfromphysicalpoint-and-windowfrompoint 1198 | 1199 | Documentation on the POINT structure: 1200 | http://msdn.microsoft.com/en-us/library/windows/desktop/dd162805(v=vs.85).aspx 1201 | """ 1202 | cursor = POINT() 1203 | cursor.x = x 1204 | cursor.y = y 1205 | hWnd = ctypes.windll.user32.WindowFromPhysicalPoint(ctypes.byref(cursor)) 1206 | if hWnd == 0: 1207 | return None 1208 | else: 1209 | return Window(hWnd) 1210 | 1211 | 1212 | def window_from_point(x, y): 1213 | """A nice wrapper for WindowFromPoint. TODO 1214 | 1215 | Syntax: 1216 | HWND WindowFromPoint( 1217 | POINT Point 1218 | ); 1219 | 1220 | Microsoft Documentation: 1221 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-windowfrompoint 1222 | 1223 | Additional Information: 1224 | https://stackoverflow.com/questions/4324954/whats-the-difference-between-windowfromphysicalpoint-and-windowfrompoint 1225 | 1226 | Documentation on the POINT structure: 1227 | http://msdn.microsoft.com/en-us/library/windows/desktop/dd162805(v=vs.85).aspx 1228 | """ 1229 | cursor = POINT() 1230 | hWnd = ctypes.windll.user32.WindowFromPhysicalPoint(ctypes.byref(cursor)) 1231 | if hWnd == 0: 1232 | return None 1233 | else: 1234 | return Window(hWnd) 1235 | 1236 | 1237 | def get_scale_factor_for_device(): 1238 | """A nice wrapper for GetScaleFactorForDevice. TODO 1239 | 1240 | Syntax: 1241 | DEVICE_SCALE_FACTOR GetScaleFactorForDevice( 1242 | DISPLAY_DEVICE_TYPE deviceType 1243 | ); 1244 | 1245 | Microsoft Documentation: 1246 | https://docs.microsoft.com/en-us/windows/desktop/api/shellscalingapi/nf-shellscalingapi-getscalefactorfordevice 1247 | 1248 | Documentation on the DEVICE_SCALE_FACTOR enum: 1249 | https://docs.microsoft.com/en-us/windows/desktop/api/shtypes/ne-shtypes-device_scale_factor 1250 | 1251 | Documentation on the DISPLAY_DEVICE_TYPE enum: 1252 | https://docs.microsoft.com/en-us/windows/desktop/api/shellscalingapi/ne-shellscalingapi-display_device_type 1253 | """ 1254 | 1255 | # TODO - returns int 150 for 150% scaled monitor. Arg 0 is "primary device" and 1 is "immersive device". 1256 | return ctypes.windll.shcore.GetScaleFactorForDevice(0) 1257 | 1258 | 1259 | def monitor_from_point(x, y, dwFlags=MONITOR_DEFAULTTONEAREST): 1260 | """A nice wrapper for MonitorFromPoint. TODO 1261 | 1262 | Returns a handle for a monitor. TODO 1263 | 1264 | Syntax: 1265 | HMONITOR MonitorFromPoint( 1266 | POINT pt, 1267 | DWORD dwFlags 1268 | ); 1269 | 1270 | Microsoft Documentation: 1271 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-monitorfrompoint 1272 | 1273 | Documentation on POINT structure: 1274 | https://docs.microsoft.com/previous-versions//dd162805(v=vs.85) 1275 | 1276 | The dwFlags parameter is one of the following: 1277 | MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTONULL, MONITOR_DEFAULTTOPRIMARY 1278 | """ 1279 | p = POINT() 1280 | p.x = x 1281 | p.y = y 1282 | return ctypes.windll.user32.MonitorFromPoint(p, dwFlags) 1283 | 1284 | 1285 | def monitor_from_rect(left, top, right, bottom, dwFlags=MONITOR_DEFAULTTONEAREST): 1286 | """A nice wrapper for MonitorFromRect. TODO 1287 | 1288 | Syntax: 1289 | HMONITOR MonitorFromRect( 1290 | LPCRECT lprc, 1291 | DWORD dwFlags 1292 | ); 1293 | 1294 | Microsoft Documentation: 1295 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-monitorfromrect 1296 | 1297 | Documentation on RECT structure: 1298 | https://docs.microsoft.com/en-us/windows/desktop/api/windef/ns-windef-rect 1299 | 1300 | The dwFlags parameter is one of the following: 1301 | MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTONULL, MONITOR_DEFAULTTOPRIMARY 1302 | """ 1303 | rect = RECT() 1304 | rect.left = left 1305 | rect.top = top 1306 | rect.right = right 1307 | rect.bottom = bottom 1308 | return ctypes.windll.user32.MonitorFromRect(ctypes.byref(rect), dwFlags) 1309 | 1310 | def monitor_from_window(hWnd, dwFlags=MONITOR_DEFAULTTONEAREST): 1311 | """A nice wrapper for MonitorFromWindow. TODO 1312 | 1313 | Syntax: 1314 | HMONITOR MonitorFromWindow( 1315 | HWND hwnd, 1316 | DWORD dwFlags 1317 | ); 1318 | 1319 | Microsoft Documentation: 1320 | https://docs.microsoft.com/en-us/windows/desktop/api/Winuser/nf-winuser-monitorfromwindow 1321 | 1322 | The dwFlags parameter is one of the following: 1323 | MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTONULL, MONITOR_DEFAULTTOPRIMARY 1324 | """ 1325 | if isinstance(hWnd, Window): 1326 | # If hWnd is actually a Window object, use it's hWnd attribute. 1327 | hWnd = hWnd.hWnd 1328 | 1329 | return ctypes.windll.user32.MonitorFromWindow(hWnd, dwFlags) 1330 | 1331 | 1332 | def get_monitor_from_window(hMonitor): 1333 | """A nice wrapper for GetMonitorFromWindowA. TODO 1334 | 1335 | Syntax: 1336 | BOOL GetMonitorInfoA( 1337 | HMONITOR hMonitor, 1338 | LPMONITORINFO lpmi 1339 | ); 1340 | 1341 | Microsoft Documentation: 1342 | https://docs.microsoft.com/en-us/windows/desktop/api/Winuser/nf-winuser-getmonitorinfoa 1343 | 1344 | Documentation on the TODO 1345 | """ 1346 | 1347 | 1348 | # TODO - need to test this 1349 | #def sound_sentry(): 1350 | # ctypes.windll.user32.SoundSentry() 1351 | 1352 | 1353 | def get_dpi_for_monitor(hMonitor): 1354 | """A nice wrappr for GetDpiForMonitor. TODP 1355 | 1356 | Syntax: 1357 | HRESULT GetDpiForMonitor( 1358 | HMONITOR hmonitor, 1359 | MONITOR_DPI_TYPE dpiType, 1360 | UINT *dpiX, 1361 | UINT *dpiY 1362 | ); 1363 | 1364 | Microsoft Documnetation: 1365 | https://docs.microsoft.com/en-us/windows/desktop/api/shellscalingapi/nf-shellscalingapi-getdpiformonitor 1366 | 1367 | """ 1368 | #ctypes.windll.shcore.GetDpiForMonitor() -------------------------------------------------------------------------------- /src/nicewin/constants.py: -------------------------------------------------------------------------------- 1 | 2 | NULL = 0 3 | 4 | # These SW_ constants are used for ShowWindow() and are documented at 5 | # https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-showwindow#parameters 6 | SW_FORCEMINIMIZE = 11 7 | SW_HIDE = 0 8 | SW_MAXIMIZE = 3 9 | SW_MINIMIZE = 6 10 | SW_RESTORE = 9 11 | SW_SHOW = 5 12 | SW_SHOWDEFAULT = 10 13 | SW_SHOWMAXIMIZED = 3 14 | SW_SHOWMINIMIZED = 2 15 | SW_SHOWMINNOACTIVE = 7 16 | SW_SHOWNA = 8 17 | SW_SHOWNOACTIVATE = 4 18 | SW_SHOWNORMAL = 1 19 | 20 | # These FORMAT_MESSAGE_ constants are used for FormatMesage() and are 21 | # documented at https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-formatmessage#parameters 22 | FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100 23 | FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000 24 | FORMAT_MESSAGE_FROM_HMODULE = 0x00000800 25 | FORMAT_MESSAGE_FROM_STRING = 0x00000400 26 | FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000 27 | FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200 28 | FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF 29 | 30 | # Language IDs documented at https://docs.microsoft.com/en-us/windows/desktop/Intl/language-identifier-constants-and-strings 31 | # More documentation at https://docs.microsoft.com/en-us/windows/desktop/Intl/language-identifiers 32 | LANG_NEUTRAL = 0x00 33 | SUBLANG_DEFAULT = 0x01 34 | 35 | # These AW_ constants are used for AnimateWindow() and are documented at 36 | # https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-animatewindow 37 | AW_ACTIVATE = 0x00020000 38 | AW_BLEND = 0x00080000 39 | AW_CENTER = 0x00000010 40 | AW_HIDE = 0x00010000 41 | AW_HOR_POSITIVE = 0x00000001 42 | AW_HOR_NEGATIVE = 0x00000002 43 | AW_SLIDE = 0x00040000 44 | AW_VER_POSITIVE = 0x00000004 45 | AW_VER_NEGATIVE = 0x00000008 46 | 47 | # These GW_ constants are used for GetWindow() and are documented at 48 | # https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getwindow#parameters 49 | GW_CHILD = 5 50 | GW_ENABLEDPOPUP = 6 51 | GW_HWNDFIRST = 0 52 | GW_HWNDLAST = 1 53 | GW_HWNDNEXT = 2 54 | GW_HWNDPREV = 3 55 | GW_OWNER = 4 56 | 57 | # These WPF_ constants are used for GetWindowPlacement() and are documented at 58 | # https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagwindowplacement#members 59 | WPF_ASYNCWINDOWPLACEMENT = 0x0004 60 | WPF_RESTORETOMAXIMIZED = 0x0002 61 | WPF_SETMINPOSITION = 0x0001 62 | 63 | # These LSFW_ constants are used for LockSetForegroundWindow() and are 64 | # documented at https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-locksetforegroundwindow 65 | LSFW_LOCK = 1 66 | LSFW_UNLOCK = 2 67 | 68 | # These MB_ constants are used for MessageBox() and are documented at 69 | # https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-messagebox#parameters 70 | # Buttons in the dialog box: 71 | MB_ABORTRETRYIGNORE = 0x00000002 72 | MB_CANCELTRYCONTINUE = 0x00000006 73 | MB_HELP = 0x00004000 74 | MB_OK = 0x00000000 75 | MB_OKCANCEL = 0x00000001 76 | MB_RETRYCANCEL = 0x00000005 77 | MB_YESNO = 0x00000004 78 | MB_YESNOCANCEL = 0x00000003 79 | 80 | # Icon to display: 81 | MB_ICONEXCLAMATION = MB_ICONWARNING = 0x00000030 82 | MB_ICONINFORMATION = MB_ICONASTERISK = 0x00000040 83 | MB_ICONQUESTION = 0x00000020 84 | MB_ICONSTOP = MB_ICONERROR = MB_ICONHAND = 0x00000010 85 | 86 | # Which button is default: 87 | MB_DEFBUTTON1 = 0x00000000 88 | MB_DEFBUTTON2 = 0x00000100 89 | MB_DEFBUTTON3 = 0x00000200 90 | MB_DEFBUTTON4 = 0x00000300 91 | 92 | # Modality of the dialog box: 93 | MB_APPLMODAL = 0x00000000 94 | MB_SYSTEMMODAL = 0x00001000 95 | MB_TASKMODAL = 0x00002000 96 | 97 | # Other options: 98 | MB_DEFAULT_DESKTOP_ONLY = 0x00020000 99 | MB_RIGHT = 0x00080000 100 | MB_RTLREADING = 0x00100000 101 | MB_SETFOREGROUND = 0x00010000 102 | MB_TOPMOST = 0x00040000 103 | MB_SERVICE_NOTIFICATION = 0x00200000 104 | 105 | # Response integers for each button type: 106 | IDABORT = 3 107 | IDCANCEL = 2 108 | IDCONTINUE = 11 109 | IDIGNORE = 5 110 | IDNO = 7 111 | IDOK = 1 112 | IDRETRY = 4 113 | IDTRYAGAIN = 10 114 | IDYES = 6 115 | 116 | # SetWindowPos constants: 117 | HWND_BOTTOM = 1 118 | HWND_TOP = 0 119 | HWND_TOPMOST = -1 120 | HWND_NOTOPMOST = -2 121 | SWP_ASYNCWINDOWPOS = 0x4000 122 | SWP_DEFERERASE = 0x2000 123 | SWP_DRAWFRAME = 0x0020 # TODO - Is this a typo in the docs? 124 | SWP_FRAMECHANGED = 0x0020 # TODO - Is this a typo in the docs? 125 | SWP_HIDEWINDOW = 0x0080 126 | SWP_NOACTIVATE = 0x0010 127 | SWP_NOCOPYBITS = 0x0100 128 | SWP_NOMOVE = 0x0002 129 | SWP_NOOWNERZORDER = 0x0200 130 | SWP_NOREDRAW = 0x0008 131 | SWP_NOREPOSITION = 0x0200 132 | SWP_NOSENDCHANGING = 0x0400 133 | SWP_NOSIZE = 0x0001 134 | SWP_NOZORDER = 0x0004 135 | SWP_SHOWWINDOW = 0x0040 136 | 137 | # Values copied from winuser.h, since they seem to absent from the MS docs. 138 | MONITOR_DEFAULTTONEAREST = 2 # Returns a handle to the display monitor that is nearest to the point. 139 | MONITOR_DEFAULTTONULL = 0 # Returns NULL. 140 | MONITOR_DEFAULTTOPRIMARY = 1 # Returns a handle to the primary display monitor. 141 | 142 | -------------------------------------------------------------------------------- /src/nicewin/structs.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | 3 | 4 | class POINT(ctypes.Structure): 5 | """A nice wrapper of the POINT structure. 6 | 7 | "The POINT structure defines the x- and y- coordinates of a point." 8 | 9 | The POINT structure is used by GetCursorPos(), WindowFromPhysicalPoint(), 10 | and other functions. 11 | 12 | Syntax: 13 | 14 | typedef struct tagPOINT { 15 | LONG x; 16 | LONG y; 17 | } POINT, *PPOINT; 18 | 19 | Microsoft Documentation: 20 | http://msdn.microsoft.com/en-us/library/windows/desktop/dd162805(v=vs.85).aspx 21 | """ 22 | _fields_ = [('x', ctypes.c_long), 23 | ('y', ctypes.c_long)] 24 | 25 | class RECT(ctypes.Structure): 26 | """A nice wrapper of the RECT structure. 27 | 28 | Syntax: 29 | typedef struct _RECT { 30 | LONG left; 31 | LONG top; 32 | LONG right; 33 | LONG bottom; 34 | } RECT, *PRECT; 35 | 36 | Microsoft Documentation: 37 | https://msdn.microsoft.com/en-us/library/windows/desktop/dd162897(v=vs.85).aspx 38 | """ 39 | _fields_ = [('left', ctypes.c_long), 40 | ('top', ctypes.c_long), 41 | ('right', ctypes.c_long), 42 | ('bottom', ctypes.c_long)] 43 | 44 | 45 | class WINDOWPLACEMENT(ctypes.Structure): 46 | """A nice wrapper of the WINDOWPLACEMENT structure. 47 | 48 | Syntax: 49 | typedef struct tagWINDOWPLACEMENT { 50 | UINT length; 51 | UINT flags; 52 | UINT showCmd; 53 | POINT ptMinPosition; 54 | POINT ptMaxPosition; 55 | RECT rcNormalPosition; 56 | RECT rcDevice; 57 | } WINDOWPLACEMENT; 58 | 59 | Microsoft Documentation: 60 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagwindowplacement 61 | """ 62 | _fields_ = [('length', ctypes.c_uint), 63 | ('flags', ctypes.c_uint), 64 | ('showCmd', ctypes.c_uint), 65 | ('ptMinPosition', POINT), 66 | ('ptMaxPosition', POINT), 67 | ('rcNormalPosition', RECT), 68 | ('rcDevice', RECT)] 69 | 70 | 71 | class WCRANGE(ctypes.Structure): 72 | """A nice wrapper of the WCRANGE structure. 73 | 74 | Syntax: 75 | typedef struct tagWCRANGE { 76 | WCHAR wcLow; 77 | USHORT cGlyphs; 78 | } WCRANGE, *PWCRANGE, *LPWCRANGE; 79 | 80 | WCHAR docs: 81 | https://docs.microsoft.com/en-us/windows/desktop/extensible-storage-engine/wchar 82 | 83 | Microsoft Documentation: 84 | https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/ns-wingdi-tagwcrange 85 | """ 86 | _fields_ = [('wcLow', ctypes.c_wchar), # TODO - Previously I used c_ushort, but then switch to c_wchar. WCHAR has different definitions depending on the system. Is it okay to just use ushort for it? 87 | ('cGlyphs', ctypes.c_ushort),] 88 | 89 | 90 | class GLYPHSET(ctypes.Structure): 91 | """A nice wrapper of the GLYPHSET structure. 92 | 93 | Syntax: 94 | typedef struct tagGLYPHSET { 95 | DWORD cbThis; 96 | DWORD flAccel; 97 | DWORD cGlyphsSupported; 98 | DWORD cRanges; 99 | WCRANGE ranges[1]; 100 | } GLYPHSET, *PGLYPHSET, *LPGLYPHSET; 101 | 102 | Microsoft Documentation: 103 | https://docs.microsoft.com/en-us/windows/desktop/api/wingdi/ns-wingdi-tagglyphset 104 | """ 105 | _fields_ = [('cbThis', ctypes.c_long), 106 | ('flAccel', ctypes.c_long), 107 | ('cGlyphsSupproted', ctypes.c_long), 108 | ('cRanges', ctypes.c_long), 109 | ('ranges', WCRANGE)] # TODO - not sure how to handle ranges[1] param. Is this a pointer? 110 | 111 | 112 | 113 | class MONITORINFO(ctypes.Structure): 114 | """A nice wrapper of the MONITORINFO structure. 115 | 116 | Syntax: 117 | typedef struct tagMONITORINFO { 118 | DWORD cbSize; 119 | RECT rcMonitor; 120 | RECT rcWork; 121 | DWORD dwFlags; 122 | } MONITORINFO, *LPMONITORINFO; 123 | 124 | Microsoft Documentation: 125 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagmonitorinfo 126 | """ 127 | _fields_ = [('cbSize', ctypes.c_long), 128 | ('rcMonitor', RECT), 129 | ('rcWork', RECT), 130 | ('dwFlags', ctypes.c_long)] 131 | 132 | 133 | class MONITORINFOEXA(ctypes.Structure): 134 | """A nice wrapper of the MONITORINFOEXA structure. TODO 135 | 136 | TODO - There's also MONITORINFOEXW, which doesn't have the MONITORINFO information but is necessary if the device name uses non-ascii characters. 137 | 138 | Syntax: 139 | typedef struct tagMONITORINFOEXA { 140 | CHAR szDevice[CCHDEVICENAME]; 141 | base_class tagMONITORINFO; 142 | } MONITORINFOEXA, *LPMONITORINFOEXA; 143 | 144 | Microsoft Documentation: 145 | https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagmonitorinfoexa 146 | """ 147 | 148 | # TODO update all of these. I need to figure out how to handle char arrays and also "base_class"; which fields come first? Is "base_class" just a documentation convention? 149 | _fields_ = [('szDevice', ctypes.c_long), 150 | ('cbSize', ctypes.c_long), 151 | ('rcMonitor', RECT), 152 | ('rcWork', RECT), 153 | ('dwFlags', ctypes.c_long)] 154 | 155 | -------------------------------------------------------------------------------- /tests/test_nicewin.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | import pytest 3 | import nicewin 4 | 5 | def test_basic(): 6 | nicewin.get_active_window() 7 | 8 | 9 | if __name__ == '__main__': 10 | pytest.main() 11 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # tox (https://tox.readthedocs.io/) is a tool for running tests 2 | # in multiple virtualenvs. This configuration file will run the 3 | # test suite on all supported python versions. To use it, "pip install tox" 4 | # and then run "tox" from this directory. 5 | 6 | [tox] 7 | envlist = py34, py35, py36, py37 8 | 9 | [testenv] 10 | deps = 11 | pytest 12 | commands = 13 | pytest 14 | --------------------------------------------------------------------------------