I need to change the cursor in all windows, not just in the application, i have try this:
this.Cursor = Cursors.WaitCursor;
And this:
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
But it only changes the cursor in my application.
Any idea?
Assuming you have your own cursor file (.cur) to apply you could hack this.
First you will have to change thje default Arrow cursor in the Registry, then you will need to call some P-Invoke to allow the OS to update the current sytem paramerters so the cursor actually changes.
Somthing like:
private void ChangeCursor(string curFile)
{
Registry.SetValue(#"HKEY_CURRENT_USER\Control Panel\Cursors\", "Arrow", curFile);
SystemParametersInfo(SPI_SETCURSORS, 0, null, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
}
const int SPI_SETCURSORS = 0x0057;
const int SPIF_UPDATEINIFILE = 0x01;
const int SPIF_SENDCHANGE = 0x02;
[DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, uint? pvParam, uint fWinIni);
Usage:
ChangeCursor(#"C:\MyCursor.cur");
You cannot change the cursor of the entire OS without modifying the registry.
You need to modify the registry to change the cursor.
See here for a tutorial and the exact Registry keys you need to modify - programmatically.
http://www.thebitguru.com/articles/14-Programmatically+Changing+Windows+Mouse+Cursors
[DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
public static extern bool SystemParametersInfo(uint uiAction, uint uiParam, ref uint pvParam, uint fWinIni);
public enum SystemParametersInfoAction : uint
{
SPI_GETBEEP = 0x0001,
SPI_SETBEEP = 0x0002,
SPI_GETMOUSE = 0x0003,
SPI_SETMOUSE = 0x0004,
SPI_GETBORDER = 0x0005,
SPI_SETBORDER = 0x0006,
SPI_GETKEYBOARDSPEED = 0x000A,
SPI_SETKEYBOARDSPEED = 0x000B,
SPI_LANGDRIVER = 0x000C,
SPI_ICONHORIZONTALSPACING = 0x000D,
SPI_GETSCREENSAVETIMEOUT = 0x000E,
SPI_SETSCREENSAVETIMEOUT = 0x000F,
SPI_GETSCREENSAVEACTIVE = 0x0010,
SPI_SETSCREENSAVEACTIVE = 0x0011,
SPI_GETGRIDGRANULARITY = 0x0012,
SPI_SETGRIDGRANULARITY = 0x0013,
SPI_SETDESKWALLPAPER = 0x0014,
SPI_SETDESKPATTERN = 0x0015,
SPI_GETKEYBOARDDELAY = 0x0016,
SPI_SETKEYBOARDDELAY = 0x0017,
SPI_ICONVERTICALSPACING = 0x0018,
SPI_GETICONTITLEWRAP = 0x0019,
SPI_SETICONTITLEWRAP = 0x001A,
SPI_GETMENUDROPALIGNMENT = 0x001B,
SPI_SETMENUDROPALIGNMENT = 0x001C,
SPI_SETDOUBLECLKWIDTH = 0x001D,
SPI_SETDOUBLECLKHEIGHT = 0x001E,
SPI_GETICONTITLELOGFONT = 0x001F,
SPI_SETDOUBLECLICKTIME = 0x0020,
SPI_SETMOUSEBUTTONSWAP = 0x0021,
SPI_SETICONTITLELOGFONT = 0x0022,
SPI_GETFASTTASKSWITCH = 0x0023,
SPI_SETFASTTASKSWITCH = 0x0024,
SPI_SETDRAGFULLWINDOWS = 0x0025,
SPI_GETDRAGFULLWINDOWS = 0x0026,
SPI_GETNONCLIENTMETRICS = 0x0029,
SPI_SETNONCLIENTMETRICS = 0x002A,
SPI_GETMINIMIZEDMETRICS = 0x002B,
SPI_SETMINIMIZEDMETRICS = 0x002C,
SPI_GETICONMETRICS = 0x002D,
SPI_SETICONMETRICS = 0x002E,
SPI_SETWORKAREA = 0x002F,
SPI_GETWORKAREA = 0x0030,
SPI_SETPENWINDOWS = 0x0031,
SPI_GETHIGHCONTRAST = 0x0042,
SPI_SETHIGHCONTRAST = 0x0043,
SPI_GETKEYBOARDPREF = 0x0044,
SPI_SETKEYBOARDPREF = 0x0045,
SPI_GETSCREENREADER = 0x0046,
SPI_SETSCREENREADER = 0x0047,
SPI_GETANIMATION = 0x0048,
SPI_SETANIMATION = 0x0049,
SPI_GETFONTSMOOTHING = 0x004A,
SPI_SETFONTSMOOTHING = 0x004B,
SPI_SETDRAGWIDTH = 0x004C,
SPI_SETDRAGHEIGHT = 0x004D,
SPI_SETHANDHELD = 0x004E,
SPI_GETLOWPOWERTIMEOUT = 0x004F,
SPI_GETPOWEROFFTIMEOUT = 0x0050,
SPI_SETLOWPOWERTIMEOUT = 0x0051,
SPI_SETPOWEROFFTIMEOUT = 0x0052,
SPI_GETLOWPOWERACTIVE = 0x0053,
SPI_GETPOWEROFFACTIVE = 0x0054,
SPI_SETLOWPOWERACTIVE = 0x0055,
SPI_SETPOWEROFFACTIVE = 0x0056,
SPI_SETCURSORS = 0x0057,
SPI_SETICONS = 0x0058,
SPI_GETDEFAULTINPUTLANG = 0x0059,
SPI_SETDEFAULTINPUTLANG = 0x005A,
SPI_SETLANGTOGGLE = 0x005B,
SPI_GETWINDOWSEXTENSION = 0x005C,
SPI_SETMOUSETRAILS = 0x005D,
SPI_GETMOUSETRAILS = 0x005E,
SPI_SETSCREENSAVERRUNNING = 0x0061,
SPI_SCREENSAVERRUNNING = SPI_SETSCREENSAVERRUNNING,
SPI_GETFILTERKEYS = 0x0032,
SPI_SETFILTERKEYS = 0x0033,
SPI_GETTOGGLEKEYS = 0x0034,
SPI_SETTOGGLEKEYS = 0x0035,
SPI_GETMOUSEKEYS = 0x0036,
SPI_SETMOUSEKEYS = 0x0037,
SPI_GETSHOWSOUNDS = 0x0038,
SPI_SETSHOWSOUNDS = 0x0039,
SPI_GETSTICKYKEYS = 0x003A,
SPI_SETSTICKYKEYS = 0x003B,
SPI_GETACCESSTIMEOUT = 0x003C,
SPI_SETACCESSTIMEOUT = 0x003D,
SPI_GETSERIALKEYS = 0x003E,
SPI_SETSERIALKEYS = 0x003F,
SPI_GETSOUNDSENTRY = 0x0040,
SPI_SETSOUNDSENTRY = 0x0041,
SPI_GETSNAPTODEFBUTTON = 0x005F,
SPI_SETSNAPTODEFBUTTON = 0x0060,
SPI_GETMOUSEHOVERWIDTH = 0x0062,
SPI_SETMOUSEHOVERWIDTH = 0x0063,
SPI_GETMOUSEHOVERHEIGHT = 0x0064,
SPI_SETMOUSEHOVERHEIGHT = 0x0065,
SPI_GETMOUSEHOVERTIME = 0x0066,
SPI_SETMOUSEHOVERTIME = 0x0067,
SPI_GETWHEELSCROLLLINES = 0x0068,
SPI_SETWHEELSCROLLLINES = 0x0069,
SPI_GETMENUSHOWDELAY = 0x006A,
SPI_SETMENUSHOWDELAY = 0x006B,
SPI_GETWHEELSCROLLCHARS = 0x006C,
SPI_SETWHEELSCROLLCHARS = 0x006D,
SPI_GETSHOWIMEUI = 0x006E,
SPI_SETSHOWIMEUI = 0x006F,
SPI_GETMOUSESPEED = 0x0070,
SPI_SETMOUSESPEED = 0x0071,
SPI_GETSCREENSAVERRUNNING = 0x0072,
SPI_GETDESKWALLPAPER = 0x0073,
SPI_GETAUDIODESCRIPTION = 0x0074,
SPI_SETAUDIODESCRIPTION = 0x0075,
SPI_GETSCREENSAVESECURE = 0x0076,
SPI_SETSCREENSAVESECURE = 0x0077,
SPI_GETHUNGAPPTIMEOUT = 0x0078,
SPI_SETHUNGAPPTIMEOUT = 0x0079,
SPI_GETWAITTOKILLTIMEOUT = 0x007A,
SPI_SETWAITTOKILLTIMEOUT = 0x007B,
SPI_GETWAITTOKILLSERVICETIMEOUT = 0x007C,
SPI_SETWAITTOKILLSERVICETIMEOUT = 0x007D,
SPI_GETMOUSEDOCKTHRESHOLD = 0x007E,
SPI_SETMOUSEDOCKTHRESHOLD = 0x007F,
SPI_GETPENDOCKTHRESHOLD = 0x0080,
SPI_SETPENDOCKTHRESHOLD = 0x0081,
SPI_GETWINARRANGING = 0x0082,
SPI_SETWINARRANGING = 0x0083,
SPI_GETMOUSEDRAGOUTTHRESHOLD = 0x0084,
SPI_SETMOUSEDRAGOUTTHRESHOLD = 0x0085,
SPI_GETPENDRAGOUTTHRESHOLD = 0x0086,
SPI_SETPENDRAGOUTTHRESHOLD = 0x0087,
SPI_GETMOUSESIDEMOVETHRESHOLD = 0x0088,
SPI_SETMOUSESIDEMOVETHRESHOLD = 0x0089,
SPI_GETPENSIDEMOVETHRESHOLD = 0x008A,
SPI_SETPENSIDEMOVETHRESHOLD = 0x008B,
SPI_GETDRAGFROMMAXIMIZE = 0x008C,
SPI_SETDRAGFROMMAXIMIZE = 0x008D,
SPI_GETSNAPSIZING = 0x008E,
SPI_SETSNAPSIZING = 0x008F,
SPI_GETDOCKMOVING = 0x0090,
SPI_SETDOCKMOVING = 0x0091,
SPI_GETACTIVEWINDOWTRACKING = 0x1000,
SPI_SETACTIVEWINDOWTRACKING = 0x1001,
SPI_GETMENUANIMATION = 0x1002,
SPI_SETMENUANIMATION = 0x1003,
SPI_GETCOMBOBOXANIMATION = 0x1004,
SPI_SETCOMBOBOXANIMATION = 0x1005,
SPI_GETLISTBOXSMOOTHSCROLLING = 0x1006,
SPI_SETLISTBOXSMOOTHSCROLLING = 0x1007,
SPI_GETGRADIENTCAPTIONS = 0x1008,
SPI_SETGRADIENTCAPTIONS = 0x1009,
SPI_GETKEYBOARDCUES = 0x100A,
SPI_SETKEYBOARDCUES = 0x100B,
SPI_GETMENUUNDERLINES = SPI_GETKEYBOARDCUES,
SPI_SETMENUUNDERLINES = SPI_SETKEYBOARDCUES,
SPI_GETACTIVEWNDTRKZORDER = 0x100C,
SPI_SETACTIVEWNDTRKZORDER = 0x100D,
SPI_GETHOTTRACKING = 0x100E,
SPI_SETHOTTRACKING = 0x100F,
SPI_GETMENUFADE = 0x1012,
SPI_SETMENUFADE = 0x1013,
SPI_GETSELECTIONFADE = 0x1014,
SPI_SETSELECTIONFADE = 0x1015,
SPI_GETTOOLTIPANIMATION = 0x1016,
SPI_SETTOOLTIPANIMATION = 0x1017,
SPI_GETTOOLTIPFADE = 0x1018,
SPI_SETTOOLTIPFADE = 0x1019,
SPI_GETCURSORSHADOW = 0x101A,
SPI_SETCURSORSHADOW = 0x101B,
SPI_GETMOUSESONAR = 0x101C,
SPI_SETMOUSESONAR = 0x101D,
SPI_GETMOUSECLICKLOCK = 0x101E,
SPI_SETMOUSECLICKLOCK = 0x101F,
SPI_GETMOUSEVANISH = 0x1020,
SPI_SETMOUSEVANISH = 0x1021,
SPI_GETFLATMENU = 0x1022,
SPI_SETFLATMENU = 0x1023,
SPI_GETDROPSHADOW = 0x1024,
SPI_SETDROPSHADOW = 0x1025,
SPI_GETBLOCKSENDINPUTRESETS = 0x1026,
SPI_SETBLOCKSENDINPUTRESETS = 0x1027,
SPI_GETUIEFFECTS = 0x103E,
SPI_SETUIEFFECTS = 0x103F,
SPI_GETDISABLEOVERLAPPEDCONTENT = 0x1040,
SPI_SETDISABLEOVERLAPPEDCONTENT = 0x1041,
SPI_GETCLIENTAREAANIMATION = 0x1042,
SPI_SETCLIENTAREAANIMATION = 0x1043,
SPI_GETCLEARTYPE = 0x1048,
SPI_SETCLEARTYPE = 0x1049,
SPI_GETSPEECHRECOGNITION = 0x104A,
SPI_SETSPEECHRECOGNITION = 0x104B,
SPI_GETFOREGROUNDLOCKTIMEOUT = 0x2000,
SPI_SETFOREGROUNDLOCKTIMEOUT = 0x2001,
SPI_GETACTIVEWNDTRKTIMEOUT = 0x2002,
SPI_SETACTIVEWNDTRKTIMEOUT = 0x2003,
SPI_GETFOREGROUNDFLASHCOUNT = 0x2004,
SPI_SETFOREGROUNDFLASHCOUNT = 0x2005,
SPI_GETCARETWIDTH = 0x2006,
SPI_SETCARETWIDTH = 0x2007,
SPI_GETMOUSECLICKLOCKTIME = 0x2008,
SPI_SETMOUSECLICKLOCKTIME = 0x2009,
SPI_GETFONTSMOOTHINGTYPE = 0x200A,
SPI_SETFONTSMOOTHINGTYPE = 0x200B,
SPI_GETFONTSMOOTHINGCONTRAST = 0x200C,
SPI_SETFONTSMOOTHINGCONTRAST = 0x200D,
SPI_GETFOCUSBORDERWIDTH = 0x200E,
SPI_SETFOCUSBORDERWIDTH = 0x200F,
SPI_GETFOCUSBORDERHEIGHT = 0x2010,
SPI_SETFOCUSBORDERHEIGHT = 0x2011,
SPI_GETFONTSMOOTHINGORIENTATION = 0x2012,
SPI_SETFONTSMOOTHINGORIENTATION = 0x2013,
SPI_GETMINIMUMHITRADIUS = 0x2014,
SPI_SETMINIMUMHITRADIUS = 0x2015,
SPI_GETMESSAGEDURATION = 0x2016,
SPI_SETMESSAGEDURATION = 0x2017,
}
Using C# with .Net 4+ or Standard 2.0 or Windows API, I would like to get the value of an environment variable for all users that are logged in, let's call the variable "Identifier". The variable for these sessions is set programmatically (by code I don't control) after they log in. The "Identifier" can be different each time they log in.
How can I get the current value of the "Identifier" environment variable from a session other than the one my process is running under, or is it not possible?
User environment variables are accessible under HKEY_USERS[SID]\Environment. You can use the following to search for a specific environment variable:
(NOTE: Machine level variables are in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment. The does not look for those. Those should be available under the same session your process is running in so it's unrelated to the original quesion regarding session specific variables.)
Put following in a new class:
static class WinApis
{
[DllImport("Secur32.dll", SetLastError = false)]
private static extern NtStatus LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);
[DllImport("secur32.dll", SetLastError = false)]
private static extern NtStatus LsaFreeReturnBuffer([In] IntPtr buffer);
[DllImport("Secur32.dll", SetLastError = false)]
private static extern uint LsaGetLogonSessionData(IntPtr luid, out IntPtr ppLogonSessionData);
private enum NtStatus : uint
{
// Success
Success = 0x00000000,
Wait0 = 0x00000000,
Wait1 = 0x00000001,
Wait2 = 0x00000002,
Wait3 = 0x00000003,
Wait63 = 0x0000003f,
Abandoned = 0x00000080,
AbandonedWait0 = 0x00000080,
AbandonedWait1 = 0x00000081,
AbandonedWait2 = 0x00000082,
AbandonedWait3 = 0x00000083,
AbandonedWait63 = 0x000000bf,
UserApc = 0x000000c0,
KernelApc = 0x00000100,
Alerted = 0x00000101,
Timeout = 0x00000102,
Pending = 0x00000103,
Reparse = 0x00000104,
MoreEntries = 0x00000105,
NotAllAssigned = 0x00000106,
SomeNotMapped = 0x00000107,
OpLockBreakInProgress = 0x00000108,
VolumeMounted = 0x00000109,
RxActCommitted = 0x0000010a,
NotifyCleanup = 0x0000010b,
NotifyEnumDir = 0x0000010c,
NoQuotasForAccount = 0x0000010d,
PrimaryTransportConnectFailed = 0x0000010e,
PageFaultTransition = 0x00000110,
PageFaultDemandZero = 0x00000111,
PageFaultCopyOnWrite = 0x00000112,
PageFaultGuardPage = 0x00000113,
PageFaultPagingFile = 0x00000114,
CrashDump = 0x00000116,
ReparseObject = 0x00000118,
NothingToTerminate = 0x00000122,
ProcessNotInJob = 0x00000123,
ProcessInJob = 0x00000124,
ProcessCloned = 0x00000129,
FileLockedWithOnlyReaders = 0x0000012a,
FileLockedWithWriters = 0x0000012b,
// Informational
Informational = 0x40000000,
ObjectNameExists = 0x40000000,
ThreadWasSuspended = 0x40000001,
WorkingSetLimitRange = 0x40000002,
ImageNotAtBase = 0x40000003,
RegistryRecovered = 0x40000009,
// Warning
Warning = 0x80000000,
GuardPageViolation = 0x80000001,
DatatypeMisalignment = 0x80000002,
Breakpoint = 0x80000003,
SingleStep = 0x80000004,
BufferOverflow = 0x80000005,
NoMoreFiles = 0x80000006,
HandlesClosed = 0x8000000a,
PartialCopy = 0x8000000d,
DeviceBusy = 0x80000011,
InvalidEaName = 0x80000013,
EaListInconsistent = 0x80000014,
NoMoreEntries = 0x8000001a,
LongJump = 0x80000026,
DllMightBeInsecure = 0x8000002b,
// Error
Error = 0xc0000000,
Unsuccessful = 0xc0000001,
NotImplemented = 0xc0000002,
InvalidInfoClass = 0xc0000003,
InfoLengthMismatch = 0xc0000004,
AccessViolation = 0xc0000005,
InPageError = 0xc0000006,
PagefileQuota = 0xc0000007,
InvalidHandle = 0xc0000008,
BadInitialStack = 0xc0000009,
BadInitialPc = 0xc000000a,
InvalidCid = 0xc000000b,
TimerNotCanceled = 0xc000000c,
InvalidParameter = 0xc000000d,
NoSuchDevice = 0xc000000e,
NoSuchFile = 0xc000000f,
InvalidDeviceRequest = 0xc0000010,
EndOfFile = 0xc0000011,
WrongVolume = 0xc0000012,
NoMediaInDevice = 0xc0000013,
NoMemory = 0xc0000017,
NotMappedView = 0xc0000019,
UnableToFreeVm = 0xc000001a,
UnableToDeleteSection = 0xc000001b,
IllegalInstruction = 0xc000001d,
AlreadyCommitted = 0xc0000021,
AccessDenied = 0xc0000022,
BufferTooSmall = 0xc0000023,
ObjectTypeMismatch = 0xc0000024,
NonContinuableException = 0xc0000025,
BadStack = 0xc0000028,
NotLocked = 0xc000002a,
NotCommitted = 0xc000002d,
InvalidParameterMix = 0xc0000030,
ObjectNameInvalid = 0xc0000033,
ObjectNameNotFound = 0xc0000034,
ObjectNameCollision = 0xc0000035,
ObjectPathInvalid = 0xc0000039,
ObjectPathNotFound = 0xc000003a,
ObjectPathSyntaxBad = 0xc000003b,
DataOverrun = 0xc000003c,
DataLate = 0xc000003d,
DataError = 0xc000003e,
CrcError = 0xc000003f,
SectionTooBig = 0xc0000040,
PortConnectionRefused = 0xc0000041,
InvalidPortHandle = 0xc0000042,
SharingViolation = 0xc0000043,
QuotaExceeded = 0xc0000044,
InvalidPageProtection = 0xc0000045,
MutantNotOwned = 0xc0000046,
SemaphoreLimitExceeded = 0xc0000047,
PortAlreadySet = 0xc0000048,
SectionNotImage = 0xc0000049,
SuspendCountExceeded = 0xc000004a,
ThreadIsTerminating = 0xc000004b,
BadWorkingSetLimit = 0xc000004c,
IncompatibleFileMap = 0xc000004d,
SectionProtection = 0xc000004e,
EasNotSupported = 0xc000004f,
EaTooLarge = 0xc0000050,
NonExistentEaEntry = 0xc0000051,
NoEasOnFile = 0xc0000052,
EaCorruptError = 0xc0000053,
FileLockConflict = 0xc0000054,
LockNotGranted = 0xc0000055,
DeletePending = 0xc0000056,
CtlFileNotSupported = 0xc0000057,
UnknownRevision = 0xc0000058,
RevisionMismatch = 0xc0000059,
InvalidOwner = 0xc000005a,
InvalidPrimaryGroup = 0xc000005b,
NoImpersonationToken = 0xc000005c,
CantDisableMandatory = 0xc000005d,
NoLogonServers = 0xc000005e,
NoSuchLogonSession = 0xc000005f,
NoSuchPrivilege = 0xc0000060,
PrivilegeNotHeld = 0xc0000061,
InvalidAccountName = 0xc0000062,
UserExists = 0xc0000063,
NoSuchUser = 0xc0000064,
GroupExists = 0xc0000065,
NoSuchGroup = 0xc0000066,
MemberInGroup = 0xc0000067,
MemberNotInGroup = 0xc0000068,
LastAdmin = 0xc0000069,
WrongPassword = 0xc000006a,
IllFormedPassword = 0xc000006b,
PasswordRestriction = 0xc000006c,
LogonFailure = 0xc000006d,
AccountRestriction = 0xc000006e,
InvalidLogonHours = 0xc000006f,
InvalidWorkstation = 0xc0000070,
PasswordExpired = 0xc0000071,
AccountDisabled = 0xc0000072,
NoneMapped = 0xc0000073,
TooManyLuidsRequested = 0xc0000074,
LuidsExhausted = 0xc0000075,
InvalidSubAuthority = 0xc0000076,
InvalidAcl = 0xc0000077,
InvalidSid = 0xc0000078,
InvalidSecurityDescr = 0xc0000079,
ProcedureNotFound = 0xc000007a,
InvalidImageFormat = 0xc000007b,
NoToken = 0xc000007c,
BadInheritanceAcl = 0xc000007d,
RangeNotLocked = 0xc000007e,
DiskFull = 0xc000007f,
ServerDisabled = 0xc0000080,
ServerNotDisabled = 0xc0000081,
TooManyGuidsRequested = 0xc0000082,
GuidsExhausted = 0xc0000083,
InvalidIdAuthority = 0xc0000084,
AgentsExhausted = 0xc0000085,
InvalidVolumeLabel = 0xc0000086,
SectionNotExtended = 0xc0000087,
NotMappedData = 0xc0000088,
ResourceDataNotFound = 0xc0000089,
ResourceTypeNotFound = 0xc000008a,
ResourceNameNotFound = 0xc000008b,
ArrayBoundsExceeded = 0xc000008c,
FloatDenormalOperand = 0xc000008d,
FloatDivideByZero = 0xc000008e,
FloatInexactResult = 0xc000008f,
FloatInvalidOperation = 0xc0000090,
FloatOverflow = 0xc0000091,
FloatStackCheck = 0xc0000092,
FloatUnderflow = 0xc0000093,
IntegerDivideByZero = 0xc0000094,
IntegerOverflow = 0xc0000095,
PrivilegedInstruction = 0xc0000096,
TooManyPagingFiles = 0xc0000097,
FileInvalid = 0xc0000098,
InstanceNotAvailable = 0xc00000ab,
PipeNotAvailable = 0xc00000ac,
InvalidPipeState = 0xc00000ad,
PipeBusy = 0xc00000ae,
IllegalFunction = 0xc00000af,
PipeDisconnected = 0xc00000b0,
PipeClosing = 0xc00000b1,
PipeConnected = 0xc00000b2,
PipeListening = 0xc00000b3,
InvalidReadMode = 0xc00000b4,
IoTimeout = 0xc00000b5,
FileForcedClosed = 0xc00000b6,
ProfilingNotStarted = 0xc00000b7,
ProfilingNotStopped = 0xc00000b8,
NotSameDevice = 0xc00000d4,
FileRenamed = 0xc00000d5,
CantWait = 0xc00000d8,
PipeEmpty = 0xc00000d9,
CantTerminateSelf = 0xc00000db,
InternalError = 0xc00000e5,
InvalidParameter1 = 0xc00000ef,
InvalidParameter2 = 0xc00000f0,
InvalidParameter3 = 0xc00000f1,
InvalidParameter4 = 0xc00000f2,
InvalidParameter5 = 0xc00000f3,
InvalidParameter6 = 0xc00000f4,
InvalidParameter7 = 0xc00000f5,
InvalidParameter8 = 0xc00000f6,
InvalidParameter9 = 0xc00000f7,
InvalidParameter10 = 0xc00000f8,
InvalidParameter11 = 0xc00000f9,
InvalidParameter12 = 0xc00000fa,
MappedFileSizeZero = 0xc000011e,
TooManyOpenedFiles = 0xc000011f,
Cancelled = 0xc0000120,
CannotDelete = 0xc0000121,
InvalidComputerName = 0xc0000122,
FileDeleted = 0xc0000123,
SpecialAccount = 0xc0000124,
SpecialGroup = 0xc0000125,
SpecialUser = 0xc0000126,
MembersPrimaryGroup = 0xc0000127,
FileClosed = 0xc0000128,
TooManyThreads = 0xc0000129,
ThreadNotInProcess = 0xc000012a,
TokenAlreadyInUse = 0xc000012b,
PagefileQuotaExceeded = 0xc000012c,
CommitmentLimit = 0xc000012d,
InvalidImageLeFormat = 0xc000012e,
InvalidImageNotMz = 0xc000012f,
InvalidImageProtect = 0xc0000130,
InvalidImageWin16 = 0xc0000131,
LogonServer = 0xc0000132,
DifferenceAtDc = 0xc0000133,
SynchronizationRequired = 0xc0000134,
DllNotFound = 0xc0000135,
IoPrivilegeFailed = 0xc0000137,
OrdinalNotFound = 0xc0000138,
EntryPointNotFound = 0xc0000139,
ControlCExit = 0xc000013a,
PortNotSet = 0xc0000353,
DebuggerInactive = 0xc0000354,
CallbackBypass = 0xc0000503,
PortClosed = 0xc0000700,
MessageLost = 0xc0000701,
InvalidMessage = 0xc0000702,
RequestCanceled = 0xc0000703,
RecursiveDispatch = 0xc0000704,
LpcReceiveBufferExpected = 0xc0000705,
LpcInvalidConnectionUsage = 0xc0000706,
LpcRequestsNotAllowed = 0xc0000707,
ResourceInUse = 0xc0000708,
ProcessIsProtected = 0xc0000712,
VolumeDirty = 0xc0000806,
FileCheckedOut = 0xc0000901,
CheckOutRequired = 0xc0000902,
BadFileType = 0xc0000903,
FileTooLarge = 0xc0000904,
FormsAuthRequired = 0xc0000905,
VirusInfected = 0xc0000906,
VirusDeleted = 0xc0000907,
TransactionalConflict = 0xc0190001,
InvalidTransaction = 0xc0190002,
TransactionNotActive = 0xc0190003,
TmInitializationFailed = 0xc0190004,
RmNotActive = 0xc0190005,
RmMetadataCorrupt = 0xc0190006,
TransactionNotJoined = 0xc0190007,
DirectoryNotRm = 0xc0190008,
CouldNotResizeLog = 0xc0190009,
TransactionsUnsupportedRemote = 0xc019000a,
LogResizeInvalidSize = 0xc019000b,
RemoteFileVersionMismatch = 0xc019000c,
CrmProtocolAlreadyExists = 0xc019000f,
TransactionPropagationFailed = 0xc0190010,
CrmProtocolNotFound = 0xc0190011,
TransactionSuperiorExists = 0xc0190012,
TransactionRequestNotValid = 0xc0190013,
TransactionNotRequested = 0xc0190014,
TransactionAlreadyAborted = 0xc0190015,
TransactionAlreadyCommitted = 0xc0190016,
TransactionInvalidMarshallBuffer = 0xc0190017,
CurrentTransactionNotValid = 0xc0190018,
LogGrowthFailed = 0xc0190019,
ObjectNoLongerExists = 0xc0190021,
StreamMiniversionNotFound = 0xc0190022,
StreamMiniversionNotValid = 0xc0190023,
MiniversionInaccessibleFromSpecifiedTransaction = 0xc0190024,
CantOpenMiniversionWithModifyIntent = 0xc0190025,
CantCreateMoreStreamMiniversions = 0xc0190026,
HandleNoLongerValid = 0xc0190028,
NoTxfMetadata = 0xc0190029,
LogCorruptionDetected = 0xc0190030,
CantRecoverWithHandleOpen = 0xc0190031,
RmDisconnected = 0xc0190032,
EnlistmentNotSuperior = 0xc0190033,
RecoveryNotNeeded = 0xc0190034,
RmAlreadyStarted = 0xc0190035,
FileIdentityNotPersistent = 0xc0190036,
CantBreakTransactionalDependency = 0xc0190037,
CantCrossRmBoundary = 0xc0190038,
TxfDirNotEmpty = 0xc0190039,
IndoubtTransactionsExist = 0xc019003a,
TmVolatile = 0xc019003b,
RollbackTimerExpired = 0xc019003c,
TxfAttributeCorrupt = 0xc019003d,
EfsNotAllowedInTransaction = 0xc019003e,
TransactionalOpenNotAllowed = 0xc019003f,
TransactedMappingUnsupportedRemote = 0xc0190040,
TxfMetadataAlreadyPresent = 0xc0190041,
TransactionScopeCallbacksNotSet = 0xc0190042,
TransactionRequiredPromotion = 0xc0190043,
CannotExecuteFileInTransaction = 0xc0190044,
TransactionsNotFrozen = 0xc0190045,
MaximumNtStatus = 0xffffffff
}
[StructLayout(LayoutKind.Sequential)]
private struct LSA_UNICODE_STRING
{
public UInt16 Length;
public UInt16 MaximumLength;
public IntPtr buffer;
}
[StructLayout(LayoutKind.Sequential)]
private struct LUID
{
public UInt32 LowPart;
public UInt32 HighPart;
}
[StructLayout(LayoutKind.Sequential)]
private struct SECURITY_LOGON_SESSION_DATA
{
public UInt32 Size;
public LUID LoginID;
public LSA_UNICODE_STRING Username;
public LSA_UNICODE_STRING LoginDomain;
public LSA_UNICODE_STRING AuthenticationPackage;
public UInt32 LogonType;
public UInt32 Session;
public IntPtr PSiD;
public UInt64 LoginTime;
public LSA_UNICODE_STRING LogonServer;
public LSA_UNICODE_STRING DnsDomainName;
public LSA_UNICODE_STRING Upn;
}
private enum SECURITY_LOGON_TYPE : uint
{
Interactive = 2, //The security principal is logging on interactively.
Network, //The security principal is logging using a network.
Batch, //The logon is for a batch process.
Service, //The logon is for a service account.
Proxy, //Not supported.
Unlock, //The logon is an attempt to unlock a workstation.
NetworkCleartext, //The logon is a network logon with cleartext credentials.
NewCredentials, // Allows the caller to clone its current token and specify new credentials for outbound connections.
RemoteInteractive, // A terminal server session that is both remote and interactive.
CachedInteractive, // Attempt to use the cached credentials without going out across the network.
CachedRemoteInteractive, // Same as RemoteInteractive, except used internally for auditing purposes.
CachedUnlock // The logon is an attempt to unlock a workstation.
}
public static List<string> GetSessionEnvironmentValue(string variableName, string userFilter="")
{
// Based on: https://stackoverflow.com/questions/27826595/wtsenumeratesessions-hangs-and-never-returns
// Which appears similar to PS script: https://www.pinvoke.net/default.aspx/secur32/LsaEnumerateLogonSessions.html
var outList = new List<string>();
System.Security.Principal.WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
DateTime systime = new DateTime(1601, 1, 1, 0, 0, 0, 0); //win32 systemdate
UInt64 count;
IntPtr luidPtr = IntPtr.Zero;
LsaEnumerateLogonSessions(out count, out luidPtr); //gets an array of pointers to LUIDs
IntPtr iter = luidPtr; //set the pointer to the start of the array
for (ulong i = 0; i < count; i++) //for each pointer in the array
{
IntPtr sessionData;
LsaGetLogonSessionData(iter, out sessionData);
SECURITY_LOGON_SESSION_DATA data = (SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(sessionData, typeof(SECURITY_LOGON_SESSION_DATA));
//if we have a valid logon
if (data.PSiD != IntPtr.Zero)
{
//get the security identifier for further use
System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(data.PSiD);
//extract some useful information from the session data struct
var ptrToStringUni = Marshal.PtrToStringUni(data.Username.buffer);
if (ptrToStringUni != null)
{
string username = ptrToStringUni.Trim(); //get the account username
var toStringUni = Marshal.PtrToStringUni(data.LoginDomain.buffer);
if (toStringUni != null)
{
string domain = toStringUni.Trim(); //domain for this account
var stringUni = Marshal.PtrToStringUni(data.AuthenticationPackage.buffer);
if (stringUni != null)
{
string authpackage = stringUni.Trim(); //authentication package
}
string session = data.Session.ToString();
SECURITY_LOGON_TYPE secType = (SECURITY_LOGON_TYPE)data.LogonType;
DateTime time = systime.AddTicks((long)data.LoginTime); //get the datetime the session was logged in
// get variable
var envVarVal = GetUserEnvironmentValue(sid.Value, variableName);
// Only add result to list if it meets username filter
if (envVarVal!="" && (userFilter=="" || username.ToLower().Contains(userFilter.ToLower())))
{
outList.Add($"User: {username}, EnvironVar({variableName}): {envVarVal}, SID: {sid.Value}");
}
}
}
}
iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(LUID))); //move the pointer forward
LsaFreeReturnBuffer(sessionData); //free the SECURITY_LOGON_SESSION_DATA memory in the struct
}
LsaFreeReturnBuffer(luidPtr); //free the array of LUIDs
return outList;
}
private static string GetUserEnvironmentValue(string sid, string variableName)
{
var envKey = Registry.Users.OpenSubKey($#"{sid}\Environment");
if (envKey != null)
{
var envVarVal = envKey.GetValue(variableName);
if (envVarVal!=null)
return envVarVal.ToString();
}
return "";
}
}
You could call it with a button click in winforms like so:
private void btnOthersEnvVars_Click(object sender, EventArgs e)
{
if (txtEnvVar.Text == "")
throw new Exception("You didn't supply a variable name...");
var sb = new StringBuilder();
foreach (var sessionInfo in WinApis.GetSessionEnvironmentValue(txtEnvVar.Text)) // you can add a username param as well
{
sb.AppendLine(sessionInfo);
}
Console.WriteLine(sb.ToString());
}
While this didn't give me what I ended up needing, it answers the question as stated.
I ended up going a different route because the environment variable I needed was being set within in a script/batch file or otherwise passed directly to my executable and was not able to be inspected without using some other API's...
If anyone else has a similar situation, I ending up using Gapotchenko.FX.Diagnostics.Process via nuget package and searching with something similar to this as Admin:
private void btnCurrentProcesses_Click(object sender, EventArgs e)
{
var procToFind = "Launcher";
Process[] processlist = Process.GetProcesses();
var sb = new StringBuilder();
StringDictionary env;
sb.AppendLine($"Session Count{processlist.DistinctBy((x) => x.SessionId).Count()}");
foreach (Process process in processlist
.Where((p)=>p.ProcessName.ToLower()==procToFind.ToLower())
.OrderBy((x)=>x.SessionId)
.ThenBy((x)=> x.ProcessName))
{
if (process!=null)
{
try
{
env = process.ReadEnvironmentVariables();
}
catch (Exception)
{
env = new StringDictionary();
}
}
else
{
env = new StringDictionary();
}
sb.AppendLine($"Session: {process.SessionId}, " +
$"ProcID: {process.Id}, " +
$"Process: {process.ProcessName}, " +
$"Env. Var: {env[txtEnvVar.Text]}");
}
Console.WriteLine(sb.ToString());
}
I'm getting the following error:
One or more of the input parameters to the service method is missing or invalid.
when
ObjectService.createDocument(repositoryId, objectPropertyCollection, rootFolderId, myContentStream, ObjectService.enumVersioningState.none, null, addAclcontrol, null, ref extType);
is called. This is how I have setup all of those parameters:
//Get repositoryId, and rootFolder id.
string repositoryId = RepositoryStore[contentType];
RepositoryService.cmisRepositoryInfoType repoInfo =_controller.RepositoryClient.getRepositoryInfo(repositoryId, new RepositoryService.cmisExtensionType());
string rootFolder = repoInfo.rootFolderId;
string theActualName = filename.Substring(filename.LastIndexOf("\\") + 1);
//Create a cmisContentStreamType.
ObjectService.cmisContentStreamType fileStream = new ObjectService.cmisContentStreamType();
fileStream.stream = File.ReadAllBytes(filename);
fileStream.filename = theActualName;
fileStream.length = fileStream.stream.Length.ToString();
fileStream.mimeType = "application/pdf";
//Setting the acl objects needed to create the document.
ObjectService.cmisAccessControlEntryType homeMembers = new ObjectService.cmisAccessControlEntryType();
ObjectService.cmisAccessControlEntryType owners = new ObjectService.cmisAccessControlEntryType();
ObjectService.cmisAccessControlEntryType viewers = new ObjectService.cmisAccessControlEntryType();
ObjectService.cmisAccessControlEntryType visitors = new ObjectService.cmisAccessControlEntryType();
ObjectService.cmisAccessControlPrincipalType ownersPrincipalType = new ObjectService.cmisAccessControlPrincipalType();
ownersPrincipalType.principalId = #"Home Owners";
owners.principal = ownersPrincipalType;
owners.permission = new string[] { "cmis:all" };
ObjectService.cmisAccessControlPrincipalType homePrincipalType = new ObjectService.cmisAccessControlPrincipalType();
homePrincipalType.principalId = #"Home Members";
homeMembers.principal = homePrincipalType;
homeMembers.permission = new string[] { "cmis:write" };
ObjectService.cmisAccessControlPrincipalType viewersPrincipalType = new ObjectService.cmisAccessControlPrincipalType();
homePrincipalType.principalId = #"Viewers";
homeMembers.principal = viewersPrincipalType;
homeMembers.permission = new string[] { "cmis:read" };
ObjectService.cmisAccessControlPrincipalType visitorsPrincipalType = new ObjectService.cmisAccessControlPrincipalType();
homePrincipalType.principalId = #"Home Visitors";
homeMembers.principal = visitorsPrincipalType;
homeMembers.permission = new string[] { "cmis:read" };
ObjectService.cmisAccessControlEntryType[] addAclControl = new ObjectService.cmisAccessControlEntryType[] { homeMembers, owners, viewers, visitors };
ObjectService.cmisExtensionType exttype = new ObjectService.cmisExtensionType();
ObjectService.cmisPropertiesType objectPropertyArray = MakedocumentPropertiesList(theActualName,fileStream.length);
private ObjectService.cmisPropertiesType MakedocumentPropertiesList(string fileName,string contentStreamLength)
{
List<ObjectService.cmisProperty> arrProps = new List<ObjectService.cmisProperty>();
ObjectService.cmisPropertiesType props = new ObjectService.cmisPropertiesType();
arrProps.Add(GetPropertyString("Name", "cmis:name", "mydocuemntname", "FileLeafRef"));
arrProps.Add(GetPropertyId("cmis:baseTypeId", "cmis:baseTypeId", "cmis:document", "cmis:baseTypeId"));
props.Items = arrProps.ToArray();
return props;
}
private ObjectService.cmisPropertyString GetPropertyString(string displayName, string queryName, string value, string localName)
{
ObjectService.cmisPropertyString title = new ObjectService.cmisPropertyString();
title.localName = localName;
title.displayName = displayName;
title.queryName = queryName;
title.propertyDefinitionId = displayName;
title.value = new string[] { value };
return title;
}
private ObjectService.cmisPropertyId GetPropertyId(string displayName, string queryName, string value, string localName)
{
ObjectService.cmisPropertyId id = new ObjectService.cmisPropertyId();
id.localName = localName;
id.displayName = displayName;
id.queryName = queryName;
id.propertyDefinitionId = displayName;
id.value = new string[] { value };
return id;
}
You cannot set the "cmis:baseTypeId" property, but you have to set the "cmis:objectTypeId" property. Try exchanging the id of your second property.
Apart from that, you should have a look at DotCMIS. It could save you a lot of work.
I took your code and I correct it .. now it is functional for me .. take a look :
string user = txtLogin.Text;
string password = txtPwd.Text;
DemoCMISForms.RepositoryService.RepositoryServicePortClient repService = new DemoCMISForms.RepositoryService.RepositoryServicePortClient("BasicHttpBinding_IRepositoryServicePort2");
repService.ClientCredentials.UserName.UserName = user;
repService.ClientCredentials.UserName.Password = password;
DemoCMISForms.ObjectService.ObjectServicePortClient objectService = new DemoCMISForms.ObjectService.ObjectServicePortClient("BasicHttpBinding_IObjectServicePort2");
objectService.ClientCredentials.UserName.UserName = user;
objectService.ClientCredentials.UserName.Password = password;
//Get repositoryId, and rootFolder id.
RepositoryService.cmisRepositoryInfoType repoInfo = repService.getRepositoryInfo(idRep, new RepositoryService.cmisExtensionType());
string rootFolder = repoInfo.rootFolderId;
string theActualName = textBox1.Text.Substring(textBox1.Text.LastIndexOf("\\") + 1);
//Create a cmisContentStreamType.
ObjectService.cmisContentStreamType fileStream = new ObjectService.cmisContentStreamType();
fileStream.stream = File.ReadAllBytes(textBox1.Text);
fileStream.filename = theActualName;
fileStream.length = fileStream.stream.Length.ToString();
fileStream.mimeType = "text/plain";
//Setting the acl objects needed to create the document.
ObjectService.cmisAccessControlEntryType homeMembers = new ObjectService.cmisAccessControlEntryType();
ObjectService.cmisAccessControlEntryType owners = new ObjectService.cmisAccessControlEntryType();
ObjectService.cmisAccessControlEntryType viewers = new ObjectService.cmisAccessControlEntryType();
ObjectService.cmisAccessControlEntryType visitors = new ObjectService.cmisAccessControlEntryType();
ObjectService.cmisAccessControlPrincipalType ownersPrincipalType = new ObjectService.cmisAccessControlPrincipalType();
ownersPrincipalType.principalId = #"Home Owners";
owners.principal = ownersPrincipalType;
owners.permission = new string[] { "cmis:all" };
ObjectService.cmisAccessControlPrincipalType homePrincipalType = new ObjectService.cmisAccessControlPrincipalType();
homePrincipalType.principalId = #"Home Members";
homeMembers.principal = homePrincipalType;
homeMembers.permission = new string[] { "cmis:write" };
ObjectService.cmisAccessControlPrincipalType viewersPrincipalType = new ObjectService.cmisAccessControlPrincipalType();
viewersPrincipalType.principalId = #"Viewers";
viewers.principal = viewersPrincipalType;
viewers.permission = new string[] { "cmis:read" };
ObjectService.cmisAccessControlPrincipalType visitorsPrincipalType = new ObjectService.cmisAccessControlPrincipalType();
visitorsPrincipalType.principalId = #"Home Visitors";
visitors.principal = visitorsPrincipalType;
visitors.permission = new string[] { "cmis:read" };
ObjectService.cmisAccessControlEntryType[] addAclControl = new ObjectService.cmisAccessControlEntryType[] { homeMembers, owners, viewers, visitors };
ObjectService.cmisExtensionType exttype = new ObjectService.cmisExtensionType();
ObjectService.cmisPropertiesType objectPropertyArray = MakedocumentPropertiesList(theActualName, fileStream.length);
objectService.createDocument(idRep, objectPropertyArray, idFolder, fileStream, ObjectService.enumVersioningState.major, null, addAclControl, null, ref exttype);
}
private ObjectService.cmisPropertiesType MakedocumentPropertiesList(string fileName, string contentStreamLength)
{
List<ObjectService.cmisProperty> arrProps = new List<ObjectService.cmisProperty>();
ObjectService.cmisPropertiesType props = new ObjectService.cmisPropertiesType();
arrProps.Add(GetPropertyString(fileName, "cmis:name", fileName, "FileLeafRef"));
arrProps.Add(GetPropertyId("cmis:objectTypeId", "cmis:objectTypeId", "cmis:document", "cmis:objectTypeId"));
props.Items = arrProps.ToArray();
return props;
}
private ObjectService.cmisPropertyString GetPropertyString(string displayName, string queryName, string value, string localName)
{
ObjectService.cmisPropertyString title = new ObjectService.cmisPropertyString();
title.localName = localName;
title.displayName = displayName;
title.queryName = queryName;
title.propertyDefinitionId = displayName;
title.value = new string[] { value };
return title;
}
private ObjectService.cmisPropertyId GetPropertyId(string displayName, string queryName, string value, string localName)
{
ObjectService.cmisPropertyId id = new ObjectService.cmisPropertyId();
id.localName = localName;
id.displayName = displayName;
id.queryName = queryName;
id.propertyDefinitionId = displayName;
id.value = new string[] { value };
return id;
}
I found some variables that were left unchanged after a copy paste manip! I also used this example with a text file !
Hope I helped you!
PS: I didnt handle yet the problem of document types , i just made the example functionnal with Text files.. Also the versionning in the list I'm calling from the SP Site is an issue so i have to verify before I add any document..