forked from mhammond/pywin32
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwin32apimodule.cpp
More file actions
6314 lines (5958 loc) · 286 KB
/
win32apimodule.cpp
File metadata and controls
6314 lines (5958 loc) · 286 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***********************************************************
win32apimodule.cpp -- module for interface into Win32' API
Note that this source file contains embedded documentation.
This documentation consists of marked up text inside the
C comments, and is prefixed with an '@' symbol. The source
files are processed by a tool called "autoduck" which
generates Windows .hlp files.
@doc
******************************************************************/
#define PY_SSIZE_T_CLEAN
#include "PyWinTypes.h"
#include "PyWinObjects.h"
#include "win32api_display.h"
#include "malloc.h"
#include "math.h" // for some of the date stuff...
#define SECURITY_WIN32 // required by below
#include "security.h" // for GetUserNameEx
#include "PowrProf.h"
// Identical to PyW32_BEGIN_ALLOW_THREADS except no script "{" !!!
// means variables can be declared between the blocks
#define PyW32_BEGIN_ALLOW_THREADS PyThreadState *_save = PyEval_SaveThread();
#define PyW32_END_ALLOW_THREADS PyEval_RestoreThread(_save);
#define PyW32_BLOCK_THREADS Py_BLOCK_THREADS
#if (_WIN32_WINNT < 0x0500)
// We don't get COMPUTER_NAME_FORMAT unless we bump this.
// As we use it dynamically, we don't *need* to bump it.
typedef int COMPUTER_NAME_FORMAT;
#endif
// from kernel32.dll
typedef BOOL(WINAPI *GetComputerNameExfunc)(COMPUTER_NAME_FORMAT, LPWSTR, PULONG);
static GetComputerNameExfunc pfnGetComputerNameEx = NULL;
typedef DWORD(WINAPI *GetLongPathNameAfunc)(LPCSTR, LPSTR, DWORD);
static GetLongPathNameAfunc pfnGetLongPathNameA = NULL;
typedef DWORD(WINAPI *GetLongPathNameWfunc)(LPCWSTR, LPWSTR, DWORD);
static GetLongPathNameWfunc pfnGetLongPathNameW = NULL;
typedef BOOL(WINAPI *GetHandleInformationfunc)(HANDLE, LPDWORD);
static GetHandleInformationfunc pfnGetHandleInformation = NULL;
typedef BOOL(WINAPI *SetHandleInformationfunc)(HANDLE, DWORD, DWORD);
static SetHandleInformationfunc pfnSetHandleInformation = NULL;
typedef BOOL(WINAPI *GlobalMemoryStatusExfunc)(LPMEMORYSTATUSEX);
static GlobalMemoryStatusExfunc pfnGlobalMemoryStatusEx = NULL;
typedef BOOL(WINAPI *GetSystemFileCacheSizefunc)(PSIZE_T, PSIZE_T, PDWORD);
static GetSystemFileCacheSizefunc pfnGetSystemFileCacheSize = NULL;
typedef BOOL(WINAPI *SetSystemFileCacheSizefunc)(SIZE_T, SIZE_T, DWORD);
static SetSystemFileCacheSizefunc pfnSetSystemFileCacheSize = NULL;
typedef DWORD(WINAPI *GetDllDirectoryfunc)(DWORD, LPWSTR);
static GetDllDirectoryfunc pfnGetDllDirectory = NULL;
typedef BOOL(WINAPI *SetDllDirectoryfunc)(LPCWSTR);
static SetDllDirectoryfunc pfnSetDllDirectory = NULL;
typedef BOOL(WINAPI *SetSystemPowerStatefunc)(BOOL, BOOL);
static SetSystemPowerStatefunc pfnSetSystemPowerState = NULL;
typedef BOOL(WINAPI *GetNativeSystemInfofunc)(LPSYSTEM_INFO);
static GetNativeSystemInfofunc pfnGetNativeSystemInfo = NULL;
// from secur32.dll
typedef BOOLEAN(WINAPI *GetUserNameExfunc)(EXTENDED_NAME_FORMAT, LPWSTR, PULONG);
static GetUserNameExfunc pfnGetUserNameEx = NULL;
static GetUserNameExfunc pfnGetComputerObjectName = NULL;
// from Advapi32.dll
typedef LONG(WINAPI *RegRestoreKeyfunc)(HKEY, LPCWSTR, DWORD);
static RegRestoreKeyfunc pfnRegRestoreKey = NULL;
typedef LONG(WINAPI *RegSaveKeyExfunc)(HKEY, LPCWSTR, LPSECURITY_ATTRIBUTES, DWORD);
static RegSaveKeyExfunc pfnRegSaveKeyEx = NULL;
typedef LONG(WINAPI *RegCreateKeyTransactedfunc)(HKEY, LPWSTR, DWORD, LPWSTR, DWORD, REGSAM, LPSECURITY_ATTRIBUTES,
PHKEY, LPDWORD, HANDLE, PVOID);
static RegCreateKeyTransactedfunc pfnRegCreateKeyTransacted = NULL;
typedef LONG(WINAPI *RegDeleteKeyExfunc)(HKEY, LPWSTR, REGSAM, DWORD);
static RegDeleteKeyExfunc pfnRegDeleteKeyEx = NULL;
typedef LONG(WINAPI *RegDeleteKeyTransactedfunc)(HKEY, LPWSTR, REGSAM, DWORD, HANDLE, PVOID);
static RegDeleteKeyTransactedfunc pfnRegDeleteKeyTransacted = NULL;
typedef LONG(WINAPI *RegOpenKeyTransactedfunc)(HKEY, LPWSTR, DWORD, REGSAM, PHKEY, HANDLE, PVOID);
static RegOpenKeyTransactedfunc pfnRegOpenKeyTransacted = NULL;
typedef LONG(WINAPI *RegCopyTreefunc)(HKEY, LPWSTR, HKEY);
static RegCopyTreefunc pfnRegCopyTree = NULL;
typedef LONG(WINAPI *RegDeleteTreefunc)(HKEY, LPWSTR);
static RegDeleteTreefunc pfnRegDeleteTree = NULL;
typedef LONG(WINAPI *RegOpenCurrentUserfunc)(REGSAM, PHKEY);
static RegOpenCurrentUserfunc pfnRegOpenCurrentUser = NULL;
typedef LONG(WINAPI *RegOverridePredefKeyfunc)(HKEY, HKEY);
static RegOverridePredefKeyfunc pfnRegOverridePredefKey = NULL;
// from user32.dll
typedef BOOL(WINAPI *GetLastInputInfofunc)(PLASTINPUTINFO);
static GetLastInputInfofunc pfnGetLastInputInfo = NULL;
/* error helper */
PyObject *ReturnError(char *msg, char *fnName = NULL)
{
PyObject *v = Py_BuildValue("(izs)", 0, fnName, msg);
if (v != NULL) {
PyErr_SetObject(PyWinExc_ApiError, v);
Py_DECREF(v);
}
return NULL;
}
/* error helper - GetLastError() is provided, but this is for exceptions */
PyObject *ReturnAPIError(char *fnName, long err = 0) { return PyWin_SetAPIError(fnName, err); }
PyObject *PyTuple_FromSYSTEMTIME(SYSTEMTIME &st)
{
return Py_BuildValue("hhhhhhhh", st.wYear, st.wMonth, st.wDayOfWeek, st.wDay, st.wHour, st.wMinute, st.wSecond,
st.wMilliseconds);
}
BOOL PyTuple_AsSYSTEMTIME(PyObject *ob, SYSTEMTIME &st)
{
return PyArg_ParseTuple(ob, "hhhhhhhh", &st.wYear, &st.wMonth, &st.wDayOfWeek, &st.wDay, &st.wHour, &st.wMinute,
&st.wSecond, &st.wMilliseconds);
}
// @pymethod |win32api|Beep|Generates simple tones on the speaker.
static PyObject *PyBeep(PyObject *self, PyObject *args)
{
DWORD freq;
DWORD dur;
if (!PyArg_ParseTuple(args, "ii:Beep",
&freq, // @pyparm int|freq||Specifies the frequency, in hertz, of the sound. This parameter
// must be in the range 37 through 32,767 (0x25 through 0x7FFF).
&dur)) // @pyparm int|dur||Specifies the duration, in milliseconds, of the sound.~
// One value has a special meaning: If dwDuration is - 1, the function
// operates asynchronously and produces sound until called again.
return NULL;
PyW32_BEGIN_ALLOW_THREADS BOOL ok = ::Beep(freq, dur);
PyW32_END_ALLOW_THREADS if (!ok) // @pyseeapi Beep
return ReturnAPIError("Beep");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |win32api|GetStdHandle|Returns a handle for the standard input, standard output, or standard error device
static PyObject *PyGetStdHandle(PyObject *self, PyObject *args)
{
DWORD nStdHandle;
if (!PyArg_ParseTuple(args, "i:GetStdHandle",
&nStdHandle)) // @pyparm int|handle||input, output, or error device
return NULL;
return PyWinLong_FromHANDLE(GetStdHandle(nStdHandle));
}
// @pymethod |win32api|SetStdHandle|Set the handle for the standard input, standard output, or standard error device
static PyObject *PySetStdHandle(PyObject *self, PyObject *args)
{
DWORD nStdHandle;
HANDLE hHandle;
PyObject *obHandle;
if (!PyArg_ParseTuple(
args, "iO:SetStdHandle",
&nStdHandle, // @pyparm int|handle||input, output, or error device
&obHandle)) // @pyparm <o PyHANDLE>/int|handle||A previously opened handle to be a standard handle
return NULL;
if (!PyWinObject_AsHANDLE(obHandle, &hHandle))
return NULL;
if (!::SetStdHandle(nStdHandle, hHandle))
return ReturnAPIError("SetStdHandle");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |win32api|CloseHandle|Closes an open handle.
static PyObject *PyCloseHandle(PyObject *self, PyObject *args)
{
PyObject *obHandle;
if (!PyArg_ParseTuple(args, "O:CloseHandle",
&obHandle)) // @pyparm <o PyHANDLE>/int|handle||A previously opened handle.
return NULL;
if (!PyWinObject_CloseHANDLE(obHandle))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod <o PyHANDLE>|win32api|DuplicateHandle|Duplicates a handle.
// @comm When duplicating a handle for a different process, you should either keep a
// reference to the returned PyHANDLE, or call .Detach() on it to prevent it
// from being closed prematurely.
static PyObject *PyDuplicateHandle(PyObject *self, PyObject *args)
{
HANDLE hSourceProcess, hSource, hTarget, hResult;
PyObject *obSourceProcess, *obSource, *obTarget;
BOOL bInherit;
DWORD options, access;
if (!PyArg_ParseTuple(
args, "OOOiii:DuplicateHandle",
&obSourceProcess, // @pyparm <o PyHANDLE>|hSourceProcess||Identifies the process containing the handle to
// duplicate.
&obSource, // @pyparm <o PyHANDLE>|hSource||Identifies the handle to duplicate. This is an open object
// handle that is valid in the context of the source process.
&obTarget, // @pyparm <o PyHANDLE>|hTargetProcessHandle||Identifies the process that is to receive the
// duplicated handle. The handle must have PROCESS_DUP_HANDLE access.
&access, // @pyparm int|desiredAccess||Specifies the access requested for the new handle. This parameter is
// ignored if the dwOptions parameter specifies the DUPLICATE_SAME_ACCESS flag. Otherwise, the
// flags that can be specified depend on the type of object whose handle is being duplicated. For
// the flags that can be specified for each object type, see the following Remarks section. Note
// that the new handle can have more access than the original handle.
&bInherit, // @pyparm int|bInheritHandle||Indicates whether the handle is inheritable. If TRUE, the
// duplicate handle can be inherited by new processes created by the target process. If FALSE,
// the new handle cannot be inherited.
&options)) // @pyparm int|options||Specifies optional actions. This parameter can be zero, or any
// combination of the following flags
// @flag DUPLICATE_CLOSE_SOURCE|loses the source handle. This occurs regardless of any error status returned.
// @flag DUPLICATE_SAME_ACCESS|Ignores the dwDesiredAccess parameter. The duplicate handle has the same access
// as the source handle.
return NULL;
if (!PyWinObject_AsHANDLE(obSourceProcess, &hSourceProcess))
return NULL;
if (!PyWinObject_AsHANDLE(obSource, &hSource))
return NULL;
if (!PyWinObject_AsHANDLE(obTarget, &hTarget))
return NULL;
if (!DuplicateHandle(hSourceProcess, hSource, hTarget, &hResult, access, bInherit, options))
return ReturnAPIError("DuplicateHandle");
return PyWinObject_FromHANDLE(hResult);
}
// @pymethod int|win32api|GetHandleInformation|Retrieves a handle's flags.
// @comm Not available on Win98/Me
// @rdesc Returns a combination of HANDLE_FLAG_INHERIT, HANDLE_FLAG_PROTECT_FROM_CLOSE
static PyObject *PyGetHandleInformation(PyObject *self, PyObject *args)
{
CHECK_PFN(GetHandleInformation);
PyObject *obObject;
HANDLE h;
DWORD Flags;
if (!PyArg_ParseTuple(args, "O:GetHandleInformation",
&obObject)) // @pyparm <o PyHANDLE>|Object||Handle to an object
return NULL;
if (!PyWinObject_AsHANDLE(obObject, &h))
return NULL;
if (!(*pfnGetHandleInformation)(h, &Flags))
return PyWin_SetAPIError("GetHandleInformation");
return PyLong_FromUnsignedLong(Flags);
}
// @pymethod |win32api|SetHandleInformation|Sets a handles's flags
// @comm Not available on Win98/Me
static PyObject *PySetHandleInformation(PyObject *self, PyObject *args)
{
CHECK_PFN(SetHandleInformation);
PyObject *obObject;
HANDLE h;
DWORD Mask, Flags;
if (!PyArg_ParseTuple(args, "Okk:SetHandleInformation",
&obObject, // @pyparm <o PyHANDLE>|Object||Handle to an object
&Mask, // @pyparm int|Mask||Bitmask specifying which flags should be set
&Flags)) // @pyparm int|Flags||Bitmask of flag values to be set. Valid Flags are
// HANDLE_FLAG_INHERIT, HANDLE_FLAG_PROTECT_FROM_CLOSE
return NULL;
if (!PyWinObject_AsHANDLE(obObject, &h))
return NULL;
if (!(*pfnSetHandleInformation)(h, Mask, Flags))
return PyWin_SetAPIError("SetHandleInformation");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |win32api|CopyFile|Copies an existing file to a new file
static PyObject *PyCopyFile(PyObject *self, PyObject *args)
{
BOOL failOnExist = FALSE;
PyObject *obSrc, *obDest;
if (!PyArg_ParseTuple(
args, "OO|i:CopyFile",
&obSrc, // @pyparm string|src||Name of an existing file.
&obDest, // @pyparm string|dest||Name of file to copy to.
&failOnExist)) // @pyparm int|bFailOnExist|0|Indicates if the operation should fail if the file exists.
return NULL;
TCHAR *src, *dest;
if (!PyWinObject_AsTCHAR(obSrc, &src, FALSE))
return NULL;
if (!PyWinObject_AsTCHAR(obDest, &dest, FALSE)) {
PyWinObject_FreeTCHAR(src);
return NULL;
}
PyW32_BEGIN_ALLOW_THREADS BOOL ok = ::CopyFile(src, dest, failOnExist);
PyW32_END_ALLOW_THREADS PyWinObject_FreeTCHAR(src);
PyWinObject_FreeTCHAR(dest);
if (!ok) // @pyseeapi CopyFile
return ReturnAPIError("CopyFile");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |win32api|DebugBreak|Breaks into the C debugger
static PyObject *PyDebugBreak(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":DebugBreak"))
return NULL;
// @pyseeapi DebugBreak
PyW32_BEGIN_ALLOW_THREADS DebugBreak();
PyW32_END_ALLOW_THREADS Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |win32api|DeleteFile|Deletes the specified file.
static PyObject *PyDeleteFile(PyObject *self, PyObject *args)
{
PyObject *obPath;
// @pyparm string|fileName||File to delete.
if (!PyArg_ParseTuple(args, "O:DeleteFile", &obPath))
return NULL;
TCHAR *szPath;
if (!PyWinObject_AsTCHAR(obPath, &szPath, FALSE))
return NULL;
// @pyseeapi DeleteFile
PyW32_BEGIN_ALLOW_THREADS BOOL ok = DeleteFile(szPath);
PyW32_END_ALLOW_THREADS PyWinObject_FreeTCHAR(szPath);
if (!ok)
return ReturnAPIError("DeleteFile");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod string/int|win32api|DragQueryFile|Retrieves the file names of dropped files.
static PyObject *PyDragQueryFile(PyObject *self, PyObject *args)
{
TCHAR buf[MAX_PATH];
HDROP hDrop;
PyObject *obhDrop;
int iFileNum = 0xFFFFFFFF;
if (!PyArg_ParseTuple(args, "O|i:DragQueryFile",
&obhDrop, // @pyparm int|hDrop||Handle identifying the structure containing the file names.
&iFileNum)) // @pyparm int|fileNum|0xFFFFFFFF|Specifies the index of the file to query.
return NULL;
if (!PyWinObject_AsHANDLE(obhDrop, (HANDLE *)&hDrop))
return NULL;
if (iFileNum < 0)
return Py_BuildValue("i", ::DragQueryFile(hDrop, (UINT)-1, NULL, 0));
else { // @pyseeapi DragQueryFile
PyW32_BEGIN_ALLOW_THREADS int ret = ::DragQueryFile(hDrop, iFileNum, buf, sizeof(buf) / sizeof(buf[0]));
PyW32_END_ALLOW_THREADS if (ret <= 0) return ReturnAPIError("DragQueryFile");
else return PyWinObject_FromTCHAR(buf);
}
// @rdesc If the fileNum parameter is 0xFFFFFFFF (the default) then the return value
// is an integer with the count of files dropped. If fileNum is between 0 and Count,
// the return value is a string containing the filename.<nl>
// If an error occurs, and exception is raised.
}
// @pymethod |win32api|DragFinish|Releases the memory stored by Windows for the filenames.
static PyObject *PyDragFinish(PyObject *self, PyObject *args)
{
HDROP hDrop;
PyObject *obhDrop;
// @pyparm int|hDrop||Handle identifying the structure containing the file names.
if (!PyArg_ParseTuple(args, "O:DragFinish", &obhDrop))
return NULL;
if (!PyWinObject_AsHANDLE(obhDrop, (HANDLE *)&hDrop))
return NULL;
PyW32_BEGIN_ALLOW_THREADS ::DragFinish(hDrop); // @pyseeapi DragFinish
PyW32_END_ALLOW_THREADS Py_INCREF(Py_None);
return Py_None;
}
// @pymethod str|win32api|GetEnvironmentVariable|Retrieves the value of an environment variable.
// @rdesc Returns None if environment variable is not found
static PyObject *PyGetEnvironmentVariable(PyObject *self, PyObject *args)
{
TCHAR *szVar;
PyObject *obVar, *ret = NULL;
if (!PyArg_ParseTuple(args, "O:GetEnvironmentVariable",
&obVar)) // @pyparm str|variable||The variable to get
return NULL;
if (!PyWinObject_AsTCHAR(obVar, &szVar, FALSE))
return NULL;
// @pyseeapi GetEnvironmentVariable
PyW32_BEGIN_ALLOW_THREADS DWORD size = GetEnvironmentVariable(szVar, NULL, 0);
PyW32_END_ALLOW_THREADS TCHAR *pResult = NULL;
if (!size) {
Py_INCREF(Py_None);
ret = Py_None;
}
else {
pResult = (TCHAR *)malloc(sizeof(TCHAR) * size);
if (pResult == NULL)
PyErr_NoMemory();
else {
PyW32_BEGIN_ALLOW_THREADS GetEnvironmentVariable(szVar, pResult, size);
PyW32_END_ALLOW_THREADS ret = PyWinObject_FromTCHAR(pResult);
}
}
PyWinObject_FreeTCHAR(szVar);
if (pResult)
free(pResult);
return ret;
}
// @pymethod string|win32api|GetEnvironmentVariableW|Retrieves the unicode value of an environment variable.
// @rdesc Returns None if environment variable is not found
// @pyseeapi GetEnvironmentVariableW
static PyObject *PyGetEnvironmentVariableW(PyObject *self, PyObject *args)
{
TmpWCHAR Name;
PyObject *obName;
if (!PyArg_ParseTuple(args, "O:GetEnvironmentVariableW",
&obName)) // @pyparm str|Name||The variable to retrieve
return NULL;
if (!PyWinObject_AsWCHAR(obName, &Name))
return NULL;
DWORD returned_size, allocated_size = 0;
WCHAR *pResult = NULL;
PyObject *ret = NULL;
// Call in loop to account for race condition where env var is changed between calls
while (TRUE) {
if (pResult)
free(pResult);
if (allocated_size) {
// returned_size includes NULL terminator
pResult = (WCHAR *)malloc(allocated_size * sizeof(WCHAR));
if (pResult == NULL) {
PyErr_NoMemory();
break;
}
}
Py_BEGIN_ALLOW_THREADS returned_size = GetEnvironmentVariableW(Name, pResult, allocated_size);
Py_END_ALLOW_THREADS if (!returned_size)
{
DWORD err = GetLastError();
if (err == ERROR_ENVVAR_NOT_FOUND) {
Py_INCREF(Py_None);
ret = Py_None;
}
else
PyWin_SetAPIError("GetEnvironmentVariableW", err);
break;
}
// Var may have been changed between calls, check that value still fits in buffer
if (returned_size < allocated_size) {
ret = PyWinObject_FromWCHAR(pResult, returned_size);
break;
}
allocated_size = returned_size;
}
if (pResult)
free(pResult);
return ret;
}
// @pymethod |win32api|SetEnvironmentVariableW|Creates, deletes, or changes the value of an environment variable.
static PyObject *PySetEnvironmentVariableW(PyObject *self, PyObject *args)
{
TmpWCHAR Name, Value;
PyObject *obName, *obValue;
if (!PyArg_ParseTuple(args, "OO:SetEnvironmentVariableW",
&obName, // @pyparm str|Name||Name of the environment variable
&obValue)) // @pyparm str|Value||Value to be set, or None to remove variable
return NULL;
// @pyseeapi SetEnvironmentVariable
if (!PyWinObject_AsWCHAR(obName, &Name))
return NULL;
if (!PyWinObject_AsWCHAR(obValue, &Value, TRUE))
return NULL;
if (!SetEnvironmentVariableW(Name, Value))
return PyWin_SetAPIError("SetEnvironmentVariableW");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod string|win32api|ExpandEnvironmentStrings|Expands environment-variable strings and replaces them with their
// defined values.
static PyObject *PyExpandEnvironmentStrings(PyObject *self, PyObject *args)
{
TCHAR *in;
PyObject *obin, *rc = NULL;
if (!PyArg_ParseTuple(args, "O:ExpandEnvironmentStrings",
&obin)) // @pyparm string|in||String to expand
return NULL;
if (!PyWinObject_AsTCHAR(obin, &in, FALSE))
return NULL;
// @pyseeapi ExpandEnvironmentStrings
DWORD size;
size = ExpandEnvironmentStrings(in, NULL, 0);
TCHAR *result = (TCHAR *)malloc(size * sizeof(TCHAR));
if (!result)
PyErr_NoMemory();
else {
PyW32_BEGIN_ALLOW_THREADS long lrc = ExpandEnvironmentStrings(in, result, size);
PyW32_END_ALLOW_THREADS if (lrc == 0) rc = ReturnAPIError("ExpandEnvironmentStrings");
else rc = PyWinObject_FromTCHAR(result);
}
PyWinObject_FreeTCHAR(in);
if (result)
free(result);
return rc;
}
// @pymethod (int, string)|win32api|FindExecutable|Retrieves the name and handle of the executable (.EXE) file
// associated with the specified filename.
// @pyseeapi FindExecutable
static PyObject *PyFindExecutable(PyObject *self, PyObject *args)
{
TCHAR *file = NULL, *dir = NULL;
TCHAR res[MAX_PATH];
PyObject *obfile, *obdir = Py_None, *ret = NULL;
BOOL freedir = TRUE;
if (!PyArg_ParseTuple(
args, "O|O:FindExecutable",
&obfile, // @pyparm string|filename||A file name. This can be either a document or executable file.
&obdir)) // @pyparm string|dir||The default directory.
return NULL;
if (PyWinObject_AsTCHAR(obfile, &file, FALSE) && PyWinObject_AsTCHAR(obdir, &dir, TRUE)) {
if (dir == NULL) {
dir = TEXT("");
freedir = FALSE;
}
HINSTANCE rc;
PyW32_BEGIN_ALLOW_THREADS rc = ::FindExecutable(file, dir, res);
PyW32_END_ALLOW_THREADS if (rc <= (HINSTANCE)32)
{
if (rc == (HINSTANCE)31)
PyErr_SetString(PyWinExc_ApiError, "FindExecutable: There is no association for the file");
else
PyWin_SetAPIError("FindExecutable", (int)rc);
}
else ret = Py_BuildValue("(NN)", PyWinLong_FromHANDLE(rc), PyWinObject_FromTCHAR(res));
}
PyWinObject_FreeTCHAR(file);
if (freedir)
PyWinObject_FreeTCHAR(dir);
return ret;
// @rdesc The return value is a tuple of (integer, string)<nl>
// The integer is the instance handle of the executable file associated
// with the specified filename. (This handle could also be the handle of
// a dynamic data exchange [DDE] server application.)<nl>
// The may contain the path to the DDE server started if no server responds to a request to initiate a DDE
// conversation.
// @comm The function will raise an exception if it fails.
}
// @pymethod list|win32api|FindFiles|Retrieves a list of matching filenames. An interface to the API
// FindFirstFile/FindNextFile/Find close functions.
// @rdesc Returns a sequence of <o WIN32_FIND_DATA> tuples
static PyObject *PyFindFiles(PyObject *self, PyObject *args)
{
TCHAR *fileSpec;
PyObject *obfileSpec;
// @pyparm string|fileSpec||A string that specifies a valid directory or path and filename, which can contain
// wildcard characters (* and ?).
if (!PyArg_ParseTuple(args, "O:FindFiles", &obfileSpec))
return NULL;
if (!PyWinObject_AsTCHAR(obfileSpec, &fileSpec, FALSE))
return NULL;
WIN32_FIND_DATA findData;
HANDLE hFind = INVALID_HANDLE_VALUE;
BOOL ok = TRUE;
PyObject *retList = PyList_New(0);
if (!retList) {
ok = FALSE;
goto done;
}
// @pyseeapi FindFirstFile
hFind = ::FindFirstFile(fileSpec, &findData);
if (hFind == INVALID_HANDLE_VALUE) {
DWORD rc = ::GetLastError();
if (rc != ERROR_FILE_NOT_FOUND) { // this is OK
ok = FALSE;
PyWin_SetAPIError("FindFirstFile", rc);
}
goto done;
}
while (1) {
PyObject *newItem = PyObject_FromWIN32_FIND_DATA(&findData);
if (newItem == NULL || PyList_Append(retList, newItem) == -1)
ok = FALSE;
Py_XDECREF(newItem);
if (!ok)
break;
// @pyseeapi FindNextFile
if (!FindNextFile(hFind, &findData)) {
ok = (GetLastError() == ERROR_NO_MORE_FILES);
if (!ok)
PyWin_SetAPIError("FindNextFile");
break;
}
}
done:
PyWinObject_FreeTCHAR(fileSpec);
// @pyseeapi FindClose
if (hFind != INVALID_HANDLE_VALUE)
::FindClose(hFind);
if (!ok) {
Py_XDECREF(retList);
retList = NULL;
}
return retList;
}
// @pymethod int|win32api|FindFirstChangeNotification|Creates a change notification handle and sets up initial change
// notification filter conditions.
// @rdesc Although the result is a handle, the handle can not be closed via CloseHandle() - therefore a PyHandle object
// is not used.
static PyObject *PyFindFirstChangeNotification(PyObject *self, PyObject *args)
{
DWORD dwFilter;
BOOL subDirs;
PyObject *obPathName;
// @pyparm string|pathName||Specifies the path of the directory to watch.
// @pyparm int|bSubDirs||Specifies whether the function will monitor the directory or the directory tree. If this
// parameter is TRUE, the function monitors the directory tree rooted at the specified directory; if it is FALSE, it
// monitors only the specified directory
// @pyparm int|filter||Specifies the filter conditions that satisfy a change notification wait. This parameter can
// be one or more of the following values:
// @flagh Value|Meaning
// @flag FILE_NOTIFY_CHANGE_FILE_NAME|Any file name change in the watched directory or subtree causes a change
// notification wait operation to return. Changes include renaming, creating, or deleting a file name.
// @flag FILE_NOTIFY_CHANGE_DIR_NAME|Any directory-name change in the watched directory or subtree causes a change
// notification wait operation to return. Changes include creating or deleting a directory.
// @flag FILE_NOTIFY_CHANGE_ATTRIBUTES|Any attribute change in the watched directory or subtree causes a change
// notification wait operation to return.
// @flag FILE_NOTIFY_CHANGE_SIZE|Any file-size change in the watched directory or subtree causes a change
// notification wait operation to return. The operating system detects a change in file size only when the file is
// written to the disk. For operating systems that use extensive caching, detection occurs only when the cache is
// sufficiently flushed.
// @flag FILE_NOTIFY_CHANGE_LAST_WRITE|Any change to the last write-time of files in the watched directory or
// subtree causes a change notification wait operation to return. The operating system detects a change to the last
// write-time only when the file is written to the disk. For operating systems that use extensive caching, detection
// occurs only when the cache is sufficiently flushed.
// @flag FILE_NOTIFY_CHANGE_SECURITY|Any security-descriptor change in the watched directory or subtree causes a
// change notification wait operation to return
if (!PyArg_ParseTuple(args, "Oil:FindFirstChangeNotification", &obPathName, &subDirs, &dwFilter))
return NULL;
TCHAR *pathName;
if (!PyWinObject_AsTCHAR(obPathName, &pathName, FALSE))
return NULL;
PyW32_BEGIN_ALLOW_THREADS HANDLE h = FindFirstChangeNotification(pathName, subDirs, dwFilter);
PyW32_END_ALLOW_THREADS PyWinObject_FreeTCHAR(pathName);
if (h == NULL || h == INVALID_HANDLE_VALUE)
return ReturnAPIError("FindFirstChangeNotification");
return PyWinLong_FromHANDLE(h);
}
// @pymethod |win32api|FindNextChangeNotification|Requests that the operating system signal a change notification handle
// the next time it detects an appropriate change.
static PyObject *PyFindNextChangeNotification(PyObject *self, PyObject *args)
{
HANDLE h;
PyObject *obh;
// @pyparm <o PyHANDLE>|handle||The handle returned from <om win32api.FindFirstChangeNotification>
if (!PyArg_ParseTuple(args, "O:FindNextChangeNotification", &obh))
return NULL;
if (!PyWinObject_AsHANDLE(obh, &h))
return NULL;
PyW32_BEGIN_ALLOW_THREADS BOOL ok = FindNextChangeNotification(h);
PyW32_END_ALLOW_THREADS if (!ok) return ReturnAPIError("FindNextChangeNotification");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod |win32api|FindCloseChangeNotification|Closes the change notification handle.
static PyObject *PyFindCloseChangeNotification(PyObject *self, PyObject *args)
{
HANDLE h;
PyObject *obh;
// @pyparm int|handle||The handle returned from <om win32api.FindFirstChangeNotification>
if (!PyArg_ParseTuple(args, "O:FindCloseChangeNotification", &obh))
return NULL;
if (!PyWinObject_AsHANDLE(obh, &h))
return NULL;
PyW32_BEGIN_ALLOW_THREADS BOOL ok = FindCloseChangeNotification(h);
PyW32_END_ALLOW_THREADS if (!ok) return ReturnAPIError("FindCloseChangeNotification");
Py_INCREF(Py_None);
return Py_None;
}
// @pymethod string|win32api|FormatMessageW|Returns an error message from the system error file.
static PyObject *PyFormatMessageW(PyObject *self, PyObject *args)
{
int errCode = 0;
// Accept just the error code
// @pyparm int|errCode|0|The error code to return the message for, If this value is 0,
// then GetLastError() is called to determine the error code.
if (PyArg_ParseTuple(args, "|k:FormatMessageW", &errCode)) {
if (errCode == 0)
// @pyseeapi GetLastError
errCode = GetLastError();
const int bufSize = 4096;
WCHAR buf[bufSize];
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
HMODULE hmodule = PyWin_GetErrorMessageModule(errCode);
if (hmodule)
flags |= FORMAT_MESSAGE_FROM_HMODULE;
// @pyseeapi FormatMessage
if (::FormatMessageW(flags, hmodule, errCode, 0, buf, bufSize, NULL) <= 0)
return ReturnAPIError("FormatMessageW");
return PyWinObject_FromWCHAR(buf);
}
PyErr_Clear();
// Full parameter list
// @pyparmalt1 int|flags||Flags for the call. Note that FORMAT_MESSAGE_ALLOCATE_BUFFER and
// FORMAT_MESSAGE_ARGUMENT_ARRAY will always be added.
// @pyparmalt1 int/string|source||The source object. If flags contain FORMAT_MESSAGE_FROM_HMODULE it should
// be an int or <o PyHANDLE>;
// if flags contain FORMAT_MESSAGE_FROM_STRING it should be a string;
// otherwise it is ignored.
// @pyparmalt1 int|messageId||The message ID.
// @pyparmalt1 int|languageID||The language ID.
// @pyparmalt1 [string,...]/None|inserts||The string inserts to insert.
DWORD flags, msgId, langId;
PyObject *obSource;
PyObject *obInserts, *Inserts_tuple = NULL;
WCHAR *szSource = NULL;
WCHAR **pInserts = NULL;
void *pSource;
PyObject *rc = NULL;
WCHAR *resultBuf = NULL;
long lrc;
BOOL baccessviolation = FALSE;
if (!PyArg_ParseTuple(args, "kOkkO:FormatMessageW", &flags, &obSource, &msgId, &langId, &obInserts))
goto cleanup;
if (flags & FORMAT_MESSAGE_FROM_HMODULE) {
if (!PyWinObject_AsHANDLE(obSource, (HANDLE *)&pSource))
goto cleanup;
}
else if (flags & FORMAT_MESSAGE_FROM_STRING) {
if (!PyWinObject_AsWCHAR(obSource, &szSource))
goto cleanup;
pSource = (void *)szSource;
}
else
pSource = NULL;
DWORD numInserts, i;
if (obInserts != Py_None) {
if ((Inserts_tuple = PyWinSequence_Tuple(obInserts, &numInserts)) == NULL)
goto cleanup;
/* Allocate 2 extra pointers, in case string inserts are missing.
This can still cause an access violation if 3 or more are missing.
This should also accept numeric values, but that would require actually
parsing the message format to see what inserts are expected.
*/
pInserts = (WCHAR **)malloc(sizeof(WCHAR *) * (numInserts + 2));
if (pInserts == NULL) {
PyErr_NoMemory();
goto cleanup;
}
for (i = 0; i < numInserts + 2; i++) // Make sure clean for cleanup
pInserts[i] = NULL;
for (i = 0; i < numInserts; i++) {
PyObject *subObject = PyTuple_GET_ITEM(Inserts_tuple, i);
if (!PyWinObject_AsWCHAR(subObject, pInserts + i))
goto cleanup;
}
}
flags |= (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_ARGUMENT_ARRAY);
{
PyW32_BEGIN_ALLOW_THREADS __try
{
lrc = ::FormatMessageW(flags, pSource, msgId, langId, (LPWSTR)&resultBuf, 0, (va_list *)pInserts);
}
__except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER
: EXCEPTION_CONTINUE_SEARCH)
{
baccessviolation = TRUE;
}
PyW32_END_ALLOW_THREADS
}
if (baccessviolation)
PyErr_SetString(PyExc_SystemError, "Access violation (probably due to missing string inserts)");
else if (lrc <= 0)
PyWin_SetAPIError("FormatMessageW");
else
rc = PyWinObject_FromWCHAR(resultBuf);
cleanup:
if (pInserts) {
for (i = 0; i < numInserts; i++) PyWinObject_FreeWCHAR(pInserts[i]);
free(pInserts);
}
PyWinObject_FreeWCHAR(szSource);
if (resultBuf)
LocalFree(resultBuf);
Py_XDECREF(Inserts_tuple);
return rc;
}
#ifndef DONT_HAVE_GENERATE_CONSOLE_CTRL_EVENT
// @pymethod int|win32api|GenerateConsoleCtrlEvent|Send a specified signal to a console process group that shares the
// console associated with the calling process.
static PyObject *PyGenerateConsoleCtrlEvent(PyObject *self, PyObject *args)
{
DWORD dwControlEvent, dwProcessGroupId;
if (!PyArg_ParseTuple(args, "ll:GenerateConsoleCtrlEvent",
&dwControlEvent, // @pyparm int|controlEvent||Signal to generate.
&dwProcessGroupId)) // @pyparm int|processGroupId||Process group to get signal.
return NULL;
// @pyseeapi GenerateConsoleCtrlEvent
PyW32_BEGIN_ALLOW_THREADS BOOL ok = GenerateConsoleCtrlEvent(dwControlEvent, dwProcessGroupId);
PyW32_END_ALLOW_THREADS if (!ok) return ReturnAPIError("GenerateConsoleCtrlEvent");
Py_INCREF(Py_None);
return Py_None;
}
#endif // DONT_HAVE_GENERATE_CONSOLE_CTRL_EVENT
// @pymethod int|win32api|GetLogicalDrives|Returns a bitmask representing the currently available disk drives.
static PyObject *PyGetLogicalDrives(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":GetLogicalDrives"))
return NULL;
// @pyseeapi GetLogicalDrives
DWORD rc = GetLogicalDrives();
if (rc == 0)
return ReturnAPIError("GetLogicalDrives");
return PyLong_FromLong(rc);
}
// @pymethod string|win32api|GetConsoleTitle|Returns the title for the current console.
static PyObject *PyGetConsoleTitle(PyObject *self, PyObject *args)
{
TCHAR *title = NULL;
DWORD chars_allocated = 1024, chars_returned;
PyObject *ret = NULL;
if (!PyArg_ParseTuple(args, ":GetConsoleTitle"))
return NULL;
// We used to rely on that if buffer is too small, function still copies
// as much of title as will fit, so loop until fewer characters returned
// than were allocated.
// Latest MSDN now says "If the buffer is not large enough to store
// the title, the return value is zero and GetLastError returns
// ERROR_SUCCESS."
// However, even on Vista, markh can observe this failing with an
// apparently stale error code - as if GetConsoleTitle assumes the
// error code is already 0 in that case. So we clear the error to
// solve that.
SetLastError(0);
while (TRUE) {
if (title != NULL) {
free(title);
chars_allocated *= 2;
}
title = (TCHAR *)malloc(chars_allocated * sizeof(TCHAR));
if (title == NULL)
return PyErr_Format(PyExc_MemoryError, "GetConsoleTitle: unable to allocate %d bytes",
chars_allocated * sizeof(TCHAR));
title[0] = 0;
chars_returned = GetConsoleTitle(title, chars_allocated);
if (chars_returned == 0 && GetLastError() != ERROR_SUCCESS) {
PyWin_SetAPIError("GetConsoleTitle");
break;
}
if ((chars_returned + 1) < chars_allocated) { // returned length does *not* includes the NULL terminator
ret = PyWinObject_FromTCHAR(title);
break;
}
}
free(title);
return ret;
}
// @pymethod string|win32api|GetComputerName|Returns the local computer name
static PyObject *PyGetComputerName(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":GetComputerName"))
return NULL;
// @pyseeapi GetComputerName
TCHAR buf[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = sizeof(buf) / sizeof(buf[0]);
if (GetComputerName(buf, &size) == 0)
return ReturnAPIError("GetComputerName");
return PyWinObject_FromTCHAR(buf, size);
}
// @pymethod string|win32api|GetComputerNameEx|Retrieves a NetBIOS or DNS name associated with the local computer
static PyObject *PyGetComputerNameEx(PyObject *self, PyObject *args)
{
CHECK_PFN(GetComputerNameEx);
WCHAR *formattedname = NULL;
COMPUTER_NAME_FORMAT fmt;
PyObject *ret = NULL;
ULONG nSize = 0;
BOOL ok;
// @pyseeapi GetComputerNameEx
if (!PyArg_ParseTuple(args, "i:GetComputerNameEx",
&fmt)) // @pyparm int|NameType||Value from COMPUTER_NAME_FORMAT enum, win32con.ComputerName*
return NULL;
// We always get into trouble with WinXP vs 2k error codes.
// Simply assume that if we have a size, the function gave us the correct one.
(*pfnGetComputerNameEx)(fmt, formattedname, &nSize);
if (!nSize)
return PyWin_SetAPIError("GetComputerNameExW");
formattedname = (WCHAR *)malloc(nSize * sizeof(WCHAR));
if (!formattedname)
return PyErr_NoMemory();
PyW32_BEGIN_ALLOW_THREADS ok = (*pfnGetComputerNameEx)(fmt, formattedname, &nSize);
PyW32_END_ALLOW_THREADS if (!ok)
{
PyWin_SetAPIError("GetComputerNameEx");
goto done;
}
ret = PyWinObject_FromWCHAR(formattedname);
done:
if (formattedname != NULL)
free(formattedname);
return ret;
}
// @pymethod string|win32api|GetComputerObjectName|Retrieves the local computer's name in a specified format.
static PyObject *PyGetComputerObjectName(PyObject *self, PyObject *args)
{
CHECK_PFN(GetComputerObjectName);
WCHAR *formattedname = NULL;
EXTENDED_NAME_FORMAT fmt;
PyObject *ret = NULL;
ULONG nSize = 0;
BOOL ok;
// @pyseeapi GetComputerObjectName
if (!PyArg_ParseTuple(args, "i:GetComputerObjectName",
&fmt)) // @pyparm int|NameFormat||EXTENDED_NAME_FORMAT value, win32con.Name*
return NULL;
// We always get into trouble with WinXP vs 2k error codes.
// Simply assume that if we have a size, the function gave us the correct one.
(*pfnGetComputerObjectName)(fmt, formattedname, &nSize);
if (!nSize)
return PyWin_SetAPIError("GetComputerObjectName");
formattedname = (WCHAR *)malloc(nSize * sizeof(WCHAR));
if (!formattedname)
return PyErr_NoMemory();
PyW32_BEGIN_ALLOW_THREADS ok = (*pfnGetComputerObjectName)(fmt, formattedname, &nSize);
PyW32_END_ALLOW_THREADS
if (!ok)
{
PyWin_SetAPIError("GetComputerObjectName");
goto done;
}
ret = PyWinObject_FromWCHAR(formattedname);
done:
if (formattedname != NULL)
free(formattedname);
return ret;
}
// @pymethod string|win32api|GetUserName|Returns the current user name
static PyObject *PyGetUserName(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":GetUserName"))
return NULL;
// @pyseeapi GetUserName
TCHAR buf[MAX_PATH + 1];
// Should actually use UNLEN (256), but requires an extra header
DWORD size = sizeof(buf) / sizeof(buf[0]);
if (!GetUserName(buf, &size))
return ReturnAPIError("GetUserName");
return PyWinObject_FromTCHAR(buf);
}
// @pymethod string|win32api|GetUserNameEx|Returns the current user name in format from EXTENDED_NAME_FORMAT enum
static PyObject *PyGetUserNameEx(PyObject *self, PyObject *args)
{
CHECK_PFN(GetUserNameEx);
WCHAR *formattedname = NULL;
EXTENDED_NAME_FORMAT fmt;
PyObject *ret = NULL;
ULONG nSize = 0;
BOOL ok;
// @pyseeapi GetUserNameEx
if (!PyArg_ParseTuple(args, "i:GetUserNameEx",
&fmt)) // @pyparm int|NameFormat||EXTENDED_NAME_FORMAT value, win32con.Name*
return NULL;
// We always get into trouble with WinXP vs 2k error codes.
// Simply assume that if we have a size, the function gave us the correct one.
(*pfnGetUserNameEx)(fmt, formattedname, &nSize);
if (!nSize)
return PyWin_SetAPIError("GetUserNameExW");
formattedname = (WCHAR *)malloc(nSize * sizeof(WCHAR));
if (!formattedname)
return PyErr_NoMemory();
PyW32_BEGIN_ALLOW_THREADS ok = (*pfnGetUserNameEx)(fmt, formattedname, &nSize);
PyW32_END_ALLOW_THREADS if (!ok)
{
PyWin_SetAPIError("GetUserNameEx");
goto done;