public static int HiWord(IntPtr dWord) { if ((dWord.ToInt32() & 0x80000000) == 0x80000000) return (dWord.ToInt32() >> 16); else return (dWord.ToInt32() >> 16) & 0xffff; }
/// <summary> /// 开始显示图像 /// </summary> public void Start() { if (bWorkStart) return; bWorkStart = true; byte[] lpszName = new byte[100]; hWndC = capCreateCaptureWindowA(lpszName, WS_CHILD | WS_VISIBLE, mLeft, mTop, mWidth, mHeight, mControlPtr, 0); if (hWndC.ToInt32() != 0) { try { SendMessage(hWndC, WM_CAP_SET_CALLBACK_VIDEOSTREAM, 0, 0); SendMessage(hWndC, WM_CAP_SET_CALLBACK_ERROR, 0, 0); SendMessage(hWndC, WM_CAP_SET_CALLBACK_STATUSA, 0, 0); SendMessage(hWndC, WM_CAP_DRIVER_CONNECT, 0, 0); SendMessage(hWndC, WM_CAP_SET_SCALE, 1, 0); SendMessage(hWndC, WM_CAP_SET_PREVIEWRATE, 66, 0); SendMessage(hWndC, WM_CAP_SET_OVERLAY, 1, 0); SendMessage(hWndC, WM_CAP_SET_PREVIEW, 1, 0); } catch (Exception ex) { throw; } //Global.log.Write( "SendMessage "); } return; }
/// <summary> /// Returns the axis-aligned bounding boxes for all letters of the word. These are defined in the range of [0, 1] which corresponds to the whole bounding box of the word. /// </summary> public RectangleData[] GetLetterBoundingBoxes() { if (!QCARRuntimeUtilities.IsQCAREnabled()) return new RectangleData[0]; if (mLetterBoundingBoxes == null) { var length = mText.Length; mLetterBoundingBoxes = new RectangleData[length]; var rectPtr = Marshal.AllocHGlobal(length * Marshal.SizeOf( typeof(RectangleData))); QCARWrapper.Instance.WordGetLetterBoundingBoxes(ID, rectPtr); var c = new IntPtr(rectPtr.ToInt32()); for (var i = 0; i < length; i++) { mLetterBoundingBoxes[i] = (RectangleData)Marshal.PtrToStructure(c, typeof(RectangleData)); c = new IntPtr(c.ToInt32() + Marshal.SizeOf( typeof(RectangleData))); } Marshal.FreeHGlobal(rectPtr); } return mLetterBoundingBoxes; }
public bgThread2WndProc(bgThread2 Parent) { System.Diagnostics.Debug.WriteLine("Creating ThreadWnd..."); this._bgThread2 = Parent; hwndControl = Hwnd; System.Diagnostics.Debug.WriteLine("bgThread2WndProc hWnd is 0x: "+hwndControl.ToInt32().ToString("x")); }
/// <summary> /// for testing /// </summary> /// <returns></returns> public bool PosTest1(string id, int i) { bool retVal = true; try { System.IntPtr ip = new IntPtr(i); if (ip.ToInt32() != i) { TestLibrary.TestFramework.LogError(id, String.Format("IntPtr value expect {0}", i)); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError(id, "Unexpected exception: " + e); retVal = false; } return retVal; }
private static void VerifyPointer(IntPtr ptr, long expected) { Assert.Equal(expected, ptr.ToInt64()); int expected32 = (int)expected; if (expected32 != expected) { Assert.Throws<OverflowException>(() => ptr.ToInt32()); return; } int i = ptr.ToInt32(); Assert.Equal(expected32, ptr.ToInt32()); Assert.Equal(expected.ToString(), ptr.ToString()); Assert.Equal(expected.ToString("x"), ptr.ToString("x")); Assert.Equal(ptr, new IntPtr(expected)); Assert.True(ptr == new IntPtr(expected)); Assert.False(ptr != new IntPtr(expected)); Assert.NotEqual(ptr, new IntPtr(expected + 1)); Assert.False(ptr == new IntPtr(expected + 1)); Assert.True(ptr != new IntPtr(expected + 1)); }
/// <summary> /// Requests to receive a notification when a device is attached or removed. /// </summary> /// /// <param name="devicePathName"> handle to a device. </param> /// <param name="formHandle"> handle to the window that will receive device events. </param> /// <param name="classGuid"> device interface GUID. </param> /// <param name="deviceNotificationHandle"> returned device notification handle. </param> /// /// <returns> /// True on success. /// </returns> /// internal Boolean RegisterForDeviceNotifications(String devicePathName, IntPtr formHandle, Guid classGuid, ref IntPtr deviceNotificationHandle) { // A DEV_BROADCAST_DEVICEINTERFACE header holds information about the request. DEV_BROADCAST_DEVICEINTERFACE devBroadcastDeviceInterface = new DEV_BROADCAST_DEVICEINTERFACE(); IntPtr devBroadcastDeviceInterfaceBuffer = IntPtr.Zero; Int32 size = 0; try { // Set the parameters in the DEV_BROADCAST_DEVICEINTERFACE structure. // Set the size. size = Marshal.SizeOf(devBroadcastDeviceInterface); devBroadcastDeviceInterface.dbcc_size = size; // Request to receive notifications about a class of devices. devBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; devBroadcastDeviceInterface.dbcc_reserved = 0; // Specify the interface class to receive notifications about. devBroadcastDeviceInterface.dbcc_classguid = classGuid; // Allocate memory for the buffer that holds the DEV_BROADCAST_DEVICEINTERFACE structure. devBroadcastDeviceInterfaceBuffer = Marshal.AllocHGlobal(size); // Copy the DEV_BROADCAST_DEVICEINTERFACE structure to the buffer. // Set fDeleteOld True to prevent memory leaks. Marshal.StructureToPtr(devBroadcastDeviceInterface, devBroadcastDeviceInterfaceBuffer, true); // *** // API function // summary // Request to receive notification messages when a device in an interface class // is attached or removed. // parameters // Handle to the window that will receive device events. // Pointer to a DEV_BROADCAST_DEVICEINTERFACE to specify the type of // device to send notifications for. // DEVICE_NOTIFY_WINDOW_HANDLE indicates the handle is a window handle. // Returns // Device notification handle or NULL on failure. // *** deviceNotificationHandle = RegisterDeviceNotification(formHandle, devBroadcastDeviceInterfaceBuffer, DEVICE_NOTIFY_WINDOW_HANDLE); // Marshal data from the unmanaged block devBroadcastDeviceInterfaceBuffer to // the managed object devBroadcastDeviceInterface Marshal.PtrToStructure(devBroadcastDeviceInterfaceBuffer, devBroadcastDeviceInterface); if ((deviceNotificationHandle.ToInt32() == IntPtr.Zero.ToInt32())) { return(false); } else { return(true); } } catch (Exception ex) { throw; } finally { if (devBroadcastDeviceInterfaceBuffer != IntPtr.Zero) { // Free the memory allocated previously by AllocHGlobal. Marshal.FreeHGlobal(devBroadcastDeviceInterfaceBuffer); } } }
public Vec3(IntPtr Memory) { vec = new float[3]; X = Mem.ReadFloat(Memory); Y = Mem.ReadFloat((IntPtr)(Memory.ToInt32() + sizeof(float))); Z = Mem.ReadFloat((IntPtr)(Memory.ToInt32() + (sizeof(float) * 2))); }
public IntPtr Serialize(params object[] objs) { int valueSize = Marshal.SizeOf(typeof(Value)); int IntPtrSize = Marshal.SizeOf(typeof(IntPtr)); int IntSize = Marshal.SizeOf(typeof(int)); int numElem = objs.Length; IntPtr ptr = IntPtr.Zero; if (numElem > 0) { ptr = Marshal.AllocCoTaskMem(valueSize * numElem); for (int i = 0; i < numElem; i++) { Value val; object currentObj = objs[i]; if (!(currentObj is Value)) { val = CreateValue(currentObj); } else { val = (Value)currentObj; } // Can't add an integer offset to IntPtr as you would with C/C++ pointer IntPtr data = new IntPtr(ptr.ToInt32() + valueSize * i); Marshal.WriteIntPtr(data, val.pInternalData); data = new IntPtr(data.ToInt32() + IntPtrSize); Marshal.WriteInt32(data, (int)val.Type); data = new IntPtr(data.ToInt32() + IntSize); Marshal.WriteInt64(data, (long)val.MovieId); } } return ptr; }
// 将字符串指针转换为字符串:一次性将指针对应的全部数据读完 public static string ptr2string(IntPtr ptr) { if (ptr.ToInt32() == 0) return ""; string s_unicode = Marshal.PtrToStringUni(ptr); byte[] buffer = Encoding.Unicode.GetBytes(s_unicode); string rtn = Encoding.UTF8.GetString(buffer); int idx = rtn.IndexOf((char)0); if (idx >= 0) rtn = rtn.Substring(0, idx); return rtn; }
private static byte[] IntPtrToBytes(IntPtr p, long offset, long length) { // This method converts the given pointer and offset to a byte[] representation // of the C struct EcbFileAndOffset (32 and 64-bit specific): // // struct FileAndOffset // { // ULONGLONG cbOffset; // ULONGLONG cbLength; // HANDLE hFile; // } // byte[] bytes = new byte[2 * sizeof(long) + IntPtr.Size]; // Put the offset value first for (int i = 0; i < 8; i++) bytes[i] = (byte)((offset >> 8*i) & 0xFF ); // Put the file value next for (int i = 0; i < 8; i++) bytes[8+i] = (byte)((length >> 8*i) & 0xFF ); if (IntPtr.Size == 4) { int temp = p.ToInt32(); for (int i = 0; i < 4; i++) bytes[16+i] = (byte)((temp >> 8*i) & 0xFF ); } else { long temp = p.ToInt64(); for (int i = 0; i < 8; i++) bytes[16+i] = (byte)((temp >> 8*i) & 0xFF ); } return bytes; }
public static bool SetProxy(string strProxy, string exceptions) { InternetPerConnOptionList list = new InternetPerConnOptionList(); int optionCount = string.IsNullOrEmpty(strProxy) ? 1 : (string.IsNullOrEmpty(exceptions) ? 2 : 3); InternetConnectionOption[] options = new InternetConnectionOption[optionCount]; // USE a proxy server ... options[0].m_Option = PerConnOption.INTERNET_PER_CONN_FLAGS; options[0].m_Value.m_Int = (int)((optionCount < 2) ? PerConnFlags.PROXY_TYPE_DIRECT : (PerConnFlags.PROXY_TYPE_DIRECT | PerConnFlags.PROXY_TYPE_PROXY)); // use THIS proxy server if (optionCount > 1) { options[1].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_SERVER; options[1].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(strProxy); // except for these addresses ... if (optionCount > 2) { options[2].m_Option = PerConnOption.INTERNET_PER_CONN_PROXY_BYPASS; options[2].m_Value.m_StringPtr = Marshal.StringToHGlobalAuto(exceptions); } } // default stuff list.dwSize = Marshal.SizeOf(list); list.szConnection = IntPtr.Zero; list.dwOptionCount = options.Length; list.dwOptionError = 0; int optSize = Marshal.SizeOf(typeof(InternetConnectionOption)); // make a pointer out of all that ... IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length); // copy the array over into that spot in memory ... for (int i = 0; i < options.Length; ++i) { IntPtr opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize)); Marshal.StructureToPtr(options[i], opt, false); } list.options = optionsPtr; // and then make a pointer out of the whole list IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((Int32)list.dwSize); Marshal.StructureToPtr(list, ipcoListPtr, false); // and finally, call the API method! int returnvalue = NativeMethods.InternetSetOption(IntPtr.Zero, InternetOption.INTERNET_OPTION_PER_CONNECTION_OPTION, ipcoListPtr, list.dwSize) ? -1 : 0; if (returnvalue == 0) { // get the error codes, they might be helpful returnvalue = Marshal.GetLastWin32Error(); } // FREE the data ASAP Marshal.FreeCoTaskMem(optionsPtr); Marshal.FreeCoTaskMem(ipcoListPtr); if (returnvalue > 0) { // throw the error codes, they might be helpful //throw new Win32Exception(Marshal.GetLastWin32Error()); } return(returnvalue < 0); }
internal static Int32 LOWORD(IntPtr ptr) { Int32 val32 = ptr.ToInt32(); return(val32 & 0xFFFF); }
internal static Int32 HIWORD(IntPtr ptr) { Int32 val32 = ptr.ToInt32(); return((val32 >> 16) & 0xFFFF); }
private static IntPtr CallbackFunction(Int32 code, IntPtr wParam, IntPtr lParam) { Int32 msgType = wParam.ToInt32(); Int32 vKey; string key = ""; if (code >= 0 && (msgType == 0x100 || msgType == 0x104)) { bool shift = false; IntPtr hWindow = GetForegroundWindow(); short shiftState = GetAsyncKeyState(Keys.ShiftKey); if ((shiftState & 0x8000) == 0x8000) { shift = true; } var caps = Console.CapsLock; vKey = Marshal.ReadInt32(lParam); if (vKey > 64 && vKey < 91) { if (shift | caps) { key = ((Keys)vKey).ToString(); } else { key = ((Keys)vKey).ToString().ToLower(); } } else if (vKey >= 96 && vKey <= 111) { switch (vKey) { case 96: key = "0"; break; case 97: key = "1"; break; case 98: key = "2"; break; case 99: key = "3"; break; case 100: key = "4"; break; case 101: key = "5"; break; case 102: key = "6"; break; case 103: key = "7"; break; case 104: key = "8"; break; case 105: key = "9"; break; case 106: key = "*"; break; case 107: key = "+"; break; case 108: key = "|"; break; case 109: key = "-"; break; case 110: key = "."; break; case 111: key = "/"; break; } } else if ((vKey >= 48 && vKey <= 57) || (vKey >= 186 && vKey <= 192)) { if (shift) { switch (vKey) { case 48: key = ")"; break; case 49: key = "!"; break; case 50: key = "@"; break; case 51: key = "#"; break; case 52: key = "$"; break; case 53: key = "%"; break; case 54: key = "^"; break; case 55: key = "&"; break; case 56: key = "*"; break; case 57: key = "("; break; case 186: key = ":"; break; case 187: key = "+"; break; case 188: key = "<"; break; case 189: key = "_"; break; case 190: key = ">"; break; case 191: key = "?"; break; case 192: key = "~"; break; case 219: key = "{"; break; case 220: key = "|"; break; case 221: key = "}"; break; case 222: key = "<Double Quotes>"; break; } } else { switch (vKey) { case 48: key = "0"; break; case 49: key = "1"; break; case 50: key = "2"; break; case 51: key = "3"; break; case 52: key = "4"; break; case 53: key = "5"; break; case 54: key = "6"; break; case 55: key = "7"; break; case 56: key = "8"; break; case 57: key = "9"; break; case 186: key = ";"; break; case 187: key = "="; break; case 188: key = ","; break; case 189: key = "-"; break; case 190: key = "."; break; case 191: key = "/"; break; case 192: key = "`"; break; case 219: key = "["; break; case 220: key = "\\"; break; case 221: key = "]"; break; case 222: key = "<Single Quote>"; break; } } } else { switch ((Keys)vKey) { case Keys.F1: key = "<F1>"; break; case Keys.F2: key = "<F2>"; break; case Keys.F3: key = "<F3>"; break; case Keys.F4: key = "<F4>"; break; case Keys.F5: key = "<F5>"; break; case Keys.F6: key = "<F6>"; break; case Keys.F7: key = "<F7>"; break; case Keys.F8: key = "<F8>"; break; case Keys.F9: key = "<F9>"; break; case Keys.F10: key = "<F10>"; break; case Keys.F11: key = "<F11>"; break; case Keys.F12: key = "<F12>"; break; case Keys.Insert: key = "<Insert>"; break; case Keys.Delete: key = "<Delete>"; break; case Keys.Tab: key = "<Tab>"; break; case Keys.Back: key = "<Backspace>"; break; case Keys.Enter: key = "<Enter>"; break; case Keys.Space: key = "<Space Bar>"; break; case Keys.Left: key = "<Left>"; break; case Keys.Up: key = "<Up>"; break; case Keys.Right: key = "<Right>"; break; case Keys.Down: key = "<Down>"; break; case Keys.LMenu: key = "<Alt>"; break; case Keys.RMenu: key = "<Alt>"; break; case Keys.LWin: key = "<Windows Key>"; break; case Keys.RWin: key = "<Windows Key>"; break; case Keys.LControlKey: key = "<Ctrl>"; break; case Keys.RControlKey: key = "<Ctrl>"; break; } } StringBuilder title = new StringBuilder(256); GetWindowText(hWindow, title, title.Capacity); Dictionary <string, string> props = new Dictionary <string, string>(); props["Key"] = key; props["Time"] = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt"); props["Window"] = title.ToString(); if (props["Window"] != Program.lastTitle) { string titleString = "User : "******"Window : " + props["Window"] + Environment.NewLine + "Time : " + props["Time"] + Environment.NewLine + "LogFile : " + Program.logName + Environment.NewLine + "----------------------------------------------"; Trace.WriteLine(""); Trace.WriteLine(""); Trace.WriteLine(titleString); Trace.WriteLine(""); Program.lastTitle = props["Window"]; } Trace.Write(props["Key"]); } return(CallNextHookEx(IntPtr.Zero, code, wParam, lParam)); }
// [DllImport("user32.dll")] // public static extern IntPtr BeginPaint(IntPtr hWnd, ref PAINTSTRUCT paintStruct); // // [DllImport("user32.dll")] // [return: MarshalAs(UnmanagedType.Bool)] // public static extern bool EndPaint(IntPtr hWnd, ref PAINTSTRUCT paintStruct); // #endregion #region Misc Functions public static int LoWord(IntPtr dWord) { return(dWord.ToInt32() & 0xffff); }
private IntPtr KeyboardProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode >= 0) { int virtualKey = Marshal.ReadInt32(lParam); int num = wParam.ToInt32(); Key key = KeyInterop.KeyFromVirtualKey(virtualKey); bool flag = num == WM_KEYDOWN || num == WM_SYSKEYDOWN; if (key == Key.LeftCtrl || key == Key.RightCtrl) { this.is_control_key_down = flag; } else if (key == Key.LeftAlt) { this.is_alt_key_down = flag; } else if (flag) { Debug.WriteLine($"Key: {key} flag: {flag}"); if (this.is_alt_key_down && this.is_control_key_down) { switch (key) { case Key.Home: InputSimulator.SimulateKeyDown(VirtualKeyCode.MEDIA_PLAY_PAUSE); return(new IntPtr(1)); case Key.End: InputSimulator.SimulateKeyDown(VirtualKeyCode.MEDIA_STOP); return(new IntPtr(1)); case Key.PageUp: InputSimulator.SimulateKeyDown(VirtualKeyCode.MEDIA_PREV_TRACK); return(new IntPtr(1)); case Key.PageDown: InputSimulator.SimulateKeyDown(VirtualKeyCode.MEDIA_NEXT_TRACK); return(new IntPtr(1)); case Key.Up: InputSimulator.SimulateKeyDown(VirtualKeyCode.VOLUME_UP); return(new IntPtr(1)); case Key.Down: InputSimulator.SimulateKeyDown(VirtualKeyCode.VOLUME_DOWN); return(new IntPtr(1)); } } // send mediakey press messages to specific process windows directly switch (key) { case Key.MediaPlayPause: case Key.MediaStop: case Key.MediaPreviousTrack: case Key.MediaNextTrack: SendToProcessIfNeeded(FirefoxProcessName, key, lParam); break; } } } return(Win32.CallNextHookEx(this.keyboard_hook, nCode, wParam, lParam)); }
public uint processFrame(uint instanceID, IntPtr bmpPtr) { uint ret; float time = GetTime(); ret = InvokeFunc(plugMainAddr, 3, (uint) bmpPtr.ToInt32(), instanceID); elapsedTime = GetTime() - time; return ret; }
/// <summary> /// Construct a <see cref="Derm.Render.XServerDeviceContext"/> class that opens the specified display. /// </summary> /// <param name="display"> /// A <see cref="System.IntpPtr"/> that will be argument of <see cref="Glx.XOpenDisplay"/>, indeed /// specifying the display to connect to. /// </param> /// <remarks> /// The property <see cref="WindowHandle"/> must be set to a valid value, since no window is created. The /// window handle shall be created using the display <see cref="Display"/>. /// </remarks> /// <exception cref='InvalidOperationException'> /// Exception thrown in the case it is not possible to connect with the display <paramref name="display"/>. /// </exception> public XServerDeviceContext(IntPtr display) { // Open display (follows DISPLAY environment variable) _Display = Glx.UnsafeNativeMethods.XOpenDisplay(display); KhronosApi.LogFunction("XOpenDisplay(0x0) = 0x{0}", _Display.ToString("X")); if (_Display == IntPtr.Zero) { throw new InvalidOperationException(String.Format("unable to connect to X server display {0}", display.ToInt32())); } // Need to close display _OwnDisplay = true; // Screen _Screen = Glx.UnsafeNativeMethods.XDefaultScreen(_Display); // Query GLX extensions QueryVersion(); }
/// <summary> /// 拍照 /// </summary> /// <param name="path">要保存bmp文件的路径</param> public void GrabImage(string path) { IntPtr hBmp = Marshal.StringToHGlobalAnsi(path); //将托管字符串复制到非托管内存中,并返回内存地址 VideoAPI.SendMessage(lwndC, VideoAPI.WM_CAP_FILE_SAVEDIB, 0, hBmp.ToInt32()); //将拍照图片以位图文件的方式存到硬盘指定路径 }
private static IntPtr RvaToVa(LOADED_IMAGE loadedImage, IntPtr rva) { return(RvaToVa(loadedImage, (uint)(rva.ToInt32()))); }
int pSvrGroupHandle = 0; //OPCGroup句柄 //连接OPCServer,建立相应OPCGroup组,并添加需要读写的Item private void Btn_Conn_Click(object sender, EventArgs e) { //定义变量 Type svrComponenttype; Int32 dwRequestedUpdateRate = 1000; //订阅读取速度 Int32 hClientGroup = 1; Int32 pRevUpdateRate; OpcRcw.Da.OPCITEMDEF[] ItemArray; float deadband = 0; int TimeBias = 0; //使用C#托管代码时,内存地址和GC回收不需要关心,CLR已经给我们暗箱操作 //如果在C#中调用了非托管代码,比如VC的DLL,而且它有一个回调函数,需要引用C#中的某个对象并操作,这时候需要小心 //要是非托管代码中用到的托管代码那个对象被GC给回收了,这时候就会报内存错误 //所以就要把那个对象钉住"Pin",让它的内存地址固定,而不被垃圾回收掉,然后我们自己管理,自己释放内存,这时候就需要GCHandle GCHandle hTimeBias, hDeadband; hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned); hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned); Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID; try { svrComponenttype = Type.GetTypeFromProgID("OPC.SimaticNet", "192.168.0.102"); //OPCServer ServerObj = (OpcRcw.Da.IOPCServer)Activator.CreateInstance(svrComponenttype); //注册 try { ServerObj.AddGroup("MyOPCGroup1", //增加组 0, dwRequestedUpdateRate, hClientGroup, hTimeBias.AddrOfPinnedObject(), hDeadband.AddrOfPinnedObject(), LOCALE_ID, out pSvrGroupHandle, out pRevUpdateRate, ref iidRequiredInterface, out MyobjGroup1); IOPCSyncIO20Obj = (IOPCSyncIO)MyobjGroup1; //Query interface for sync calls on group object IOPCGroupStateMgtObj = (IOPCGroupStateMgt)MyobjGroup1; ItemArray = new OPCITEMDEF[2]; //定义读写的item,共2个变量 ItemArray[0].szAccessPath = ""; ItemArray[0].szItemID = "S7:[S7 conncetion_1]DB10,INT0"; //地址,不同数据类型表示方法不同 ItemArray[0].bActive = 1; //是否激活 ItemArray[0].hClient = 1; //表示ID ItemArray[0].dwBlobSize = 0; ItemArray[0].vtRequestedDataType = 2; ItemArray[1].szAccessPath = ""; ItemArray[1].szItemID = "S7:[S7 connection_1]DB10,STRING14.10"; ItemArray[1].bActive = 1; ItemArray[1].hClient = 2; ItemArray[1].dwBlobSize = 0; ItemArray[1].pBlob = IntPtr.Zero; ItemArray[1].vtRequestedDataType = 8; IntPtr pResults = IntPtr.Zero; IntPtr pErrors = IntPtr.Zero; try { ((OpcRcw.Da.IOPCItemMgt)MyobjGroup1).AddItems(2, ItemArray, out pResults, out pErrors); int[] errors = new int[2]; IntPtr pos = pResults; ItemServerHandle = new int[2]; Marshal.Copy(pErrors, errors, 0, 2); if (errors[0] == 0) { OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT)); ItemServerHandle[0] = result.hServer; } if (errors[1] == 0) { pos = new IntPtr(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT))); OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT)); ItemServerHandle[1] = result.hServer; } } catch (System.Exception error) { MessageBox.Show(error.Message, "Result-Adding Items", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { //free the memory if (pResults != IntPtr.Zero) { Marshal.FreeCoTaskMem(pResults); pResults = IntPtr.Zero; } if (pErrors != IntPtr.Zero) { Marshal.FreeCoTaskMem(pErrors); pErrors = IntPtr.Zero; } } } catch (System.Exception error) { MessageBox.Show(String.Format("Error while creating group object:-{0}", error.Message), "Result-Add group", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error); } finally { if (hDeadband.IsAllocated) { hDeadband.Free(); } if (hTimeBias.IsAllocated) { hTimeBias.Free(); } } } catch (System.Exception error) { MessageBox.Show(String.Format("Error while creating server object:-{0}", error.Message), "Result-Create Server", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error); } }
// 将字符串指针对应数据写入到数据流中,主要用于分段传输的数据的拼接 public static void readPtr(Stream bos, IntPtr ptr, int dataLen) { if (ptr.ToInt32() == 0) return; byte[] data = new byte[dataLen]; Marshal.Copy(ptr, data, 0, dataLen); bos.Write(data, 0, dataLen); }
protected override IntPtr Hook1Procedure(int nCode, IntPtr wParam, IntPtr lParam) { if (EnableEvents) { // If OK and someone listens to our events if (nCode >= 0) { var info = new CURSORINFO(); info.Size = Marshal.SizeOf(info.GetType()); if (!GetCursorInfo(out info)) { var ex = new System.ComponentModel.Win32Exception(); throw new Exception(ex.Message); } var button = MouseButtons.None; var param = wParam.ToInt32(); // Marshall the data from callback. var mStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)); var delta = 0; var tu = new TestUnion(mStruct.mouseData); MouseKey mk = 0; int lastX = 0; int lastY = 0; bool handled; var unknownAction = false; switch (param) { case WM_MOUSEMOVE: var x = mStruct.pt.x; var y = mStruct.pt.y; if (prevX == -1 || prevY == -1) { scrnX = SystemInformation.VirtualScreen.Width - 1; scrnY = SystemInformation.VirtualScreen.Height - 1; prevX = x; prevY = y; } lastX = x - prevX; lastY = y - prevY; var fX = (int)Math.Max(Math.Min(scrnX, x), 0); var fY = (int)Math.Max(Math.Min(scrnY, y), 0); if (fX != x || fY != y) { SetCursorPos(fX, fY); } prevX = fX; prevY = fY; break; case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_LBUTTONDBLCLK: button = MouseButtons.Left; break; case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_MBUTTONDBLCLK: button = MouseButtons.Middle; break; case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_RBUTTONDBLCLK: button = MouseButtons.Right; break; case WM_XBUTTONDOWN: case WM_XBUTTONUP: case WM_XBUTTONDBLCLK: button = MouseButtons.XButton1; if (tu.High == 1) { mk = MouseKey.MK_XBUTTON1; } if (tu.High == 2) { mk = MouseKey.MK_XBUTTON2; } break; case WM_NCXBUTTONDOWN: case WM_NCXBUTTONUP: case WM_NCXBUTTONDBLCLK: button = MouseButtons.XButton2; if (tu.High == 1) { mk = MouseKey.MK_XBUTTON1; } if (tu.High == 2) { mk = MouseKey.MK_XBUTTON2; } break; case WM_MOUSEWHEEL: case WM_MOUSEHWHEEL: delta = (int)tu.High; mk = (MouseKey)tu.ULow; break; case WM_TOUCH: try { handled = DecodeTouch(wParam, lParam); } catch (Exception ex) { if (OnError != null) { OnError(this, new UnhandledExceptionEventArgs(ex, false)); } } break; default: unknownAction = true; break; } var ea = new MouseHookEventArgs(mStruct, info, mk, param, lastX, lastY, null); if (OnMouseHook != null) { OnMouseHook(this, ea); } int clickCount = 0; if (button != MouseButtons.None) { clickCount = (param == WM_LBUTTONDBLCLK || param == WM_RBUTTONDBLCLK) ? 2 : 1; } var e = new MouseEventArgs(button, clickCount, mStruct.pt.x, mStruct.pt.y, delta); // Raise Events. if (OnMouseUp != null && (param == WM_LBUTTONUP || param == WM_MBUTTONUP || param == WM_RBUTTONUP || param == WM_XBUTTONUP || param == WM_NCXBUTTONUP)) { OnMouseUp(this, e); } else if (OnMouseDown != null && (param == WM_LBUTTONDOWN || param == WM_MBUTTONDOWN || param == WM_RBUTTONDOWN || param == WM_XBUTTONDOWN || param == WM_NCXBUTTONDOWN)) { OnMouseDown(this, e); } else if (OnMouseMove != null && (param == WM_MOUSEMOVE)) { OnMouseMove(this, e); } else if (OnMouseWheel != null) { OnMouseWheel(this, e); } else if (OnMouseActivity != null) { OnMouseActivity(this, e); } if (unknownAction) { var ev = OnMouseUnknown; if (ev != null) { ev(this, ea); } } } } return(NativeMethods.CallNextHookEx(hook1handleRef, nCode, wParam, lParam)); }
private static void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) { if ((idObject == 0) && (idChild == 0)) { if (psi.isSpotifyAvailable() && hwnd.ToInt32() == psi.getSpotifyWindowHandle().ToInt32()) { string track = tmd.getTrack(); string artist = tmd.getArtist(); if (track != null || artist != null) { //Console.WriteLine(artist + " - " + track); notify.showViaToast(myForm, track, artist); //Console.WriteLine("Finished Showing"); } } } }
protected override void Hook2Procedure( IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime ) { if (hwnd == IntPtr.Zero && idObject == OBJID_CURSOR && idChild == CHILDID_SELF) { if (eventType == EVENT_OBJECT_NAMECHANGE || eventType == EVENT_OBJECT_SHOW) { Console.WriteLine("Hook2Procedure hwnd = {0:x8}, eventType = {1:x8}, idChild = {2:x8}", hwnd.ToInt32(), eventType, idChild); var ev = OnCursorChanged; if (ev != null) { var ci = default(CURSORINFO); ci.Size = Marshal.SizeOf(ci); var success = GetCursorInfo(out ci); Bitmap image = null; if (success) { image = MouseHelper.GetCurrentCursorImage(); } var e = new MouseHookEventArgs(null, ci, 0, 0, 0, 0, image); ev(this, e); } } } }
private int Reader(int handle, IntPtr buffer, int length, IntPtr user) { return basbuffer.Read(buffer, length, user.ToInt32()); }
/// <summary> /// http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/5c8ff964-c087-43c0-a88d-0ce7719e033c /// c:\Program Files\Microsoft SDKs\Windows\v7.1\Samples\Touch\MTScratchpadWMTouch\CS\ /// </summary> private bool DecodeTouch(IntPtr wParam, IntPtr lParam) { // More than one touch input may be associated with a touch message, // so an array is needed to get all event information. int inputCount = LoWord(wParam.ToInt32()); // Number of touch inputs, actual per-contact messages var inputs = new TOUCHINPUT[inputCount]; // Allocate the storage for the parameters of the per-contact messages // Unpack message parameters into the array of TOUCHINPUT structures, each // representing a message for one single contact. var touchInputSize = Marshal.SizeOf(new TOUCHINPUT()); if (!GetTouchInputInfo(lParam, inputCount, inputs, touchInputSize)) { // Get touch info failed. return(false); } // For each contact, dispatch the message to the appropriate message // handler. bool handled = false; // Boolean, is message handled for (int i = 0; i < inputCount; i++) { TOUCHINPUT ti = inputs[i]; // Assign a handler to this message. EventHandler <MouseTouchEventArgs> handler = null; // Touch event handler if ((ti.dwFlags & TOUCHEVENTF_DOWN) != 0) { handler = OnTouchDown; } else if ((ti.dwFlags & TOUCHEVENTF_UP) != 0) { handler = OnTouchUp; } else if ((ti.dwFlags & TOUCHEVENTF_MOVE) != 0) { handler = OnTouchMove; } // Convert message parameters into touch event arguments and handle the event. if (handler != null) { // Convert the raw touch input message into a touch event. var te = new MouseTouchEventArgs(); // Touch event arguments // TOUCHINFO point coordinates and contact size is in 1/100 of a pixel; convert it to pixels. // Also convert screen to client coordinates. te.ContactY = ti.cyContact / 100; te.ContactX = ti.cxContact / 100; te.Id = ti.dwID; { te.LocationX = ti.x / 100; te.LocationY = ti.y / 100; } te.Time = ti.dwTime; te.Mask = ti.dwMask; te.Flags = ti.dwFlags; // Invoke the event handler. handler(this, te); // Mark this event as handled. handled = true; } } CloseTouchInputHandle(lParam); return(handled); }
// Update Virtual Button states. public void UpdateVirtualButtons(int numVirtualButtons, IntPtr virtualButtonPtr) { Dictionary<int, QCARManagerImpl.VirtualButtonData> vbResults = new Dictionary<int, QCARManagerImpl.VirtualButtonData>(); // create a dictionary of all results for (int i = 0; i < numVirtualButtons; i++) { IntPtr vbPtr = new IntPtr(virtualButtonPtr.ToInt32() + i* Marshal.SizeOf(typeof (QCARManagerImpl.VirtualButtonData))); QCARManagerImpl.VirtualButtonData vbData = (QCARManagerImpl.VirtualButtonData) Marshal.PtrToStructure(vbPtr, typeof (QCARManagerImpl.VirtualButtonData)); vbResults.Add(vbData.id, vbData); } List<VirtualButtonBehaviour> vbBehavioursToUpdate = new List<VirtualButtonBehaviour>(); // go over all trackable behaviours and find the virtual buttons to update foreach (TrackableBehaviour trackableBehaviour in mTrackableBehaviours.Values) { ImageTargetBehaviour it = trackableBehaviour as ImageTargetBehaviour; if (it != null && it.enabled) { foreach(VirtualButtonBehaviour virtualButtonBehaviour in it.GetVirtualButtonBehaviours()) { if (virtualButtonBehaviour.enabled) { vbBehavioursToUpdate.Add(virtualButtonBehaviour); } } } } // update the virtual buttons: foreach (VirtualButtonBehaviour virtualButtonBehaviour in vbBehavioursToUpdate) { QCARManagerImpl.VirtualButtonData vbData; if (vbResults.TryGetValue(virtualButtonBehaviour.VirtualButton.ID, out vbData)) { virtualButtonBehaviour.OnTrackerUpdated(vbData.isPressed > 0); } else { virtualButtonBehaviour.OnTrackerUpdated(false); } } }
internal static IntPtr SetWindowLong_N(IntPtr handle, GetWindowLongOffsets item, IntPtr newValue) { return(IntPtr.Size == 4 ? (IntPtr)SetWindowLong(handle, item, newValue.ToInt32()) : SetWindowLongPtr(handle, item, newValue)); }
internal static PRINTER_INFO_2[] EnumPrintersByFlag(PrinterEnumFlags Flags) { uint cbNeeded = 0; uint cReturned = 0; bool ret = EnumPrinters(PrinterEnumFlags.PRINTER_ENUM_LOCAL, null, 2, IntPtr.Zero, 0, ref cbNeeded, ref cReturned); IntPtr pAddr = Marshal.AllocHGlobal((int)cbNeeded); ret = EnumPrinters(PrinterEnumFlags.PRINTER_ENUM_LOCAL, null, 2, pAddr, cbNeeded, ref cbNeeded, ref cReturned); if (ret) { PRINTER_INFO_2[] Info2 = new PRINTER_INFO_2[cReturned]; int offset = pAddr.ToInt32(); for (int i = 0; i < cReturned; i++) { Info2[i].pServerName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pPrinterName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pShareName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pPortName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pDriverName = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pComment = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pLocation = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pDevMode = Marshal.ReadIntPtr(new IntPtr(offset)); offset += 4; Info2[i].pSepFile = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pPrintProcessor = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pDatatype = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pParameters = Marshal.PtrToStringAuto(Marshal.ReadIntPtr(new IntPtr(offset))); offset += 4; Info2[i].pSecurityDescriptor = Marshal.ReadIntPtr(new IntPtr(offset)); offset += 4; Info2[i].Attributes = (uint )Marshal.ReadIntPtr(new IntPtr(offset)); offset += 4; Info2[i].Priority = (uint)Marshal.ReadInt32(new IntPtr(offset)); offset += 4; Info2[i].DefaultPriority = (uint)Marshal.ReadInt32(new IntPtr(offset)); offset += 4; Info2[i].StartTime = (uint)Marshal.ReadInt32(new IntPtr(offset)); offset += 4; Info2[i].UntilTime = (uint)Marshal.ReadInt32(new IntPtr(offset)); offset += 4; Info2[i].Status = (uint)Marshal.ReadInt32(new IntPtr(offset)); offset += 4; Info2[i].cJobs = (uint)Marshal.ReadInt32(new IntPtr(offset)); offset += 4; Info2[i].AveragePPM = (uint)Marshal.ReadInt32(new IntPtr(offset)); offset += 4; } Marshal.FreeHGlobal(pAddr); return(Info2); } else { return(new PRINTER_INFO_2[0]); } }
/// <summary> /// Set the system proxy, as per the 'Internet Options' panel /// </summary> /// <returns>True if the operation was successful</returns> public static bool SetProxy(bool ProxyEnable, string ProxyServer, string ProxyBypass) { var options = new INTERNET_PER_CONN_OPTION[3]; // Option #1: ProxyEnable options[0].dwOption = INTERNET_PER_CONN.FLAGS; options[0].Value.i = (int)(ProxyEnable ? (PER_CONN_FLAGS.PROXY_TYPE_DIRECT | PER_CONN_FLAGS.PROXY_TYPE_PROXY) : PER_CONN_FLAGS.PROXY_TYPE_DIRECT); // Option #2: ProxyServer options[1].dwOption = INTERNET_PER_CONN.PROXY_SERVER; options[1].Value.iptr = Marshal.StringToHGlobalAuto( ProxyServer); // Option #3: ProxyBypass options[2].dwOption = INTERNET_PER_CONN.PROXY_BYPASS; options[2].Value.iptr = Marshal.StringToHGlobalAuto( ProxyBypass); var list = new INTERNET_PER_CONN_OPTION_LIST(); list.dwSize = Marshal.SizeOf(list); list.pszConnection = IntPtr.Zero; // change globally list.dwOptionCount = options.Length; list.dwOptionError = 0; // Marshall each option in options int optSize = Marshal.SizeOf(typeof(INTERNET_PER_CONN_OPTION)); IntPtr optionsPtr = Marshal.AllocCoTaskMem(optSize * options.Length); for (int i = 0; i < options.Length; ++i) { var opt = new IntPtr(optionsPtr.ToInt32() + (i * optSize)); Marshal.StructureToPtr(options[i], opt, false); } list.pOptions = optionsPtr; // and then make a pointer out of the whole list IntPtr ipcoListPtr = Marshal.AllocCoTaskMem((Int32)list.dwSize); Marshal.StructureToPtr(list, ipcoListPtr, false); // Finally, call the InternetSetOption API int res = InternetSetOption(IntPtr.Zero, INTERNET_OPTION.PER_CONNECTION_OPTION, ipcoListPtr, list.dwSize) ? -1 : 0; if (res == 0) { res = Marshal.GetLastWin32Error(); } Marshal.FreeCoTaskMem(optionsPtr); Marshal.FreeCoTaskMem(ipcoListPtr); if (res > 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } return(res < 0); }
// Convert a point to the raw pixel data to a .NET bitmap public Bitmap IPToBmp(IntPtr ip) { // We know the Bits Per Pixel is 24 (3 bytes) because we forced it // to be with sampGrabber.SetMediaType() int iBufSize = m_videoWidth * m_videoHeight * 3; return (Bitmap) new Bitmap( m_videoWidth, m_videoHeight, -m_stride, PixelFormat.Format24bppRgb, (IntPtr)(ip.ToInt32() + iBufSize - m_stride) ).GetThumbnailImage(320, 240, null, IntPtr.Zero); /* int iBufSize = 256 * 256 * 3; return (Bitmap) new Bitmap( 256, 256, -m_stride, PixelFormat.Format24bppRgb, (IntPtr)(ip.ToInt32() + iBufSize - m_stride) ); */ }
/// <summary> /// Processes incoming system messages. /// </summary> /// <param name="msg">Callback ID.</param> /// <param name="wParam">If the version is <see cref="NotifyIconVersion.Vista"/> /// or higher, this parameter can be used to resolve mouse coordinates. /// Currently not in use.</param> /// <param name="lParam">Provides information about the event.</param> private void ProcessWindowMessage(uint msg, IntPtr wParam, IntPtr lParam) { // TODO: Gereksiz eventlar kapatıldı if (msg != CallbackMessageId) { return; } var message = (WindowsMessages)lParam.ToInt32(); if (message != WindowsMessages.WM_LBUTTONDBLCLK) { return; } isDoubleClick = true; MouseEventReceived?.Invoke(MouseEvent.IconDoubleClick); //Debug.WriteLine("Got message " + message); //switch (message) //{ // case WindowsMessages.WM_CONTEXTMENU: // // TODO: Handle WM_CONTEXTMENU, see https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shell_notifyiconw // Debug.WriteLine("Unhandled WM_CONTEXTMENU"); // break; // case WindowsMessages.WM_MOUSEMOVE: // MouseEventReceived?.Invoke(MouseEvent.MouseMove); // break; // case WindowsMessages.WM_LBUTTONDOWN: // MouseEventReceived?.Invoke(MouseEvent.IconLeftMouseDown); // break; // case WindowsMessages.WM_LBUTTONUP: // if (!isDoubleClick) // { // MouseEventReceived?.Invoke(MouseEvent.IconLeftMouseUp); // } // isDoubleClick = false; // break; // case WindowsMessages.WM_LBUTTONDBLCLK: // isDoubleClick = true; // MouseEventReceived?.Invoke(MouseEvent.IconDoubleClick); // break; // case WindowsMessages.WM_RBUTTONDOWN: // MouseEventReceived?.Invoke(MouseEvent.IconRightMouseDown); // break; // case WindowsMessages.WM_RBUTTONUP: // MouseEventReceived?.Invoke(MouseEvent.IconRightMouseUp); // break; // case WindowsMessages.WM_RBUTTONDBLCLK: // //double click with right mouse button - do not trigger event // break; // case WindowsMessages.WM_MBUTTONDOWN: // MouseEventReceived?.Invoke(MouseEvent.IconMiddleMouseDown); // break; // case WindowsMessages.WM_MBUTTONUP: // MouseEventReceived?.Invoke(MouseEvent.IconMiddleMouseUp); // break; // case WindowsMessages.WM_MBUTTONDBLCLK: // //double click with middle mouse button - do not trigger event // break; // case WindowsMessages.NIN_BALLOONSHOW: // BalloonToolTipChanged?.Invoke(true); // break; // case WindowsMessages.NIN_BALLOONHIDE: // case WindowsMessages.NIN_BALLOONTIMEOUT: // BalloonToolTipChanged?.Invoke(false); // break; // case WindowsMessages.NIN_BALLOONUSERCLICK: // MouseEventReceived?.Invoke(MouseEvent.BalloonToolTipClicked); // break; // case WindowsMessages.NIN_POPUPOPEN: // ChangeToolTipStateRequest?.Invoke(true); // break; // case WindowsMessages.NIN_POPUPCLOSE: // ChangeToolTipStateRequest?.Invoke(false); // break; // case WindowsMessages.NIN_SELECT: // // TODO: Handle NIN_SELECT see https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shell_notifyiconw // Debug.WriteLine("Unhandled NIN_SELECT"); // break; // case WindowsMessages.NIN_KEYSELECT: // // TODO: Handle NIN_KEYSELECT see https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shell_notifyiconw // Debug.WriteLine("Unhandled NIN_KEYSELECT"); // break; // default: // Debug.WriteLine("Unhandled NotifyIcon message ID: " + lParam); // break; //} }
public static int RunTest(IntPtr affinity, string processName, string processArgs, int seed) { // run the test Random rand = null; Process p = Process.Start(processName, processArgs); // cannot set the affinity before the process starts in managed code // This code executes so quickly that the GC heaps have not yet been initialized, // so it works. if (affinity != IntPtr.Zero) { // set affinity to (2^n)-1, where n=affinity int newAffinity = (int)Math.Pow(2, affinity.ToInt32())-1; p.ProcessorAffinity = new IntPtr(newAffinity); Console.WriteLine("Affinitizing to {0}", newAffinity); } else { rand = new Random(seed); Console.WriteLine("Using random seed: {0}", seed); } while (!p.HasExited) { // change affinity randomly every 5 seconds Thread.Sleep(5000); if (affinity == IntPtr.Zero) { try { // randomly change the affinity between 1 and (2^n)-1, where n=numProcessors int newAffinity = rand.Next(1, (int)Math.Pow(2, Environment.ProcessorCount)-1); p.ProcessorAffinity = new IntPtr(newAffinity); Console.WriteLine("Affinitizing to {0}", newAffinity); } // we couldn't set the affinity, so just exit catch (InvalidOperationException) { break; } catch (System.ComponentModel.Win32Exception) { break; } } } Console.WriteLine("Exiting with exit code {0}", p.ExitCode); return p.ExitCode; }
static MenuItem FindItemByKey (Menu menu, IntPtr key) { char key_char = Char.ToUpper ((char) (key.ToInt32() & 0xff)); foreach (MenuItem item in menu.MenuItems) { if (item.Mnemonic == key_char) return item; } string key_str = key_char.ToString (); foreach (MenuItem item in menu.MenuItems) { //if (item.Mnemonic == key_char) if (item.Text.StartsWith (key_str)) return item; } return null; }
void processTouches(IntPtr wParam, IntPtr lParam) { int inputCount = LOWORD(wParam.ToInt32()); TOUCHINPUT[] inputs = new TOUCHINPUT[inputCount]; if (!GetTouchInputInfo(lParam, inputCount, inputs, touchInputSize)) { return; } for (int i = 0; i < inputCount; i++) { TOUCHINPUT touch = inputs[i]; updateTouchFromWM(touch); } CloseTouchInputHandle(lParam); }
private void decodeTouches( uint msg, IntPtr wParam, IntPtr lParam ) { lock( tracking ) { int xPos = LOWORD( lParam.ToInt32() ); int yPos = HIWORD( lParam.ToInt32() ); int pointerId = LOWORD( wParam.ToInt32() ); POINTER_INFO pointerInfo = new POINTER_INFO(); if( !GetPointerInfo( pointerId, ref pointerInfo ) ) { return; } POINT p = new POINT() { X = xPos, Y = yPos }; ScreenToClient( hMainWindow, ref p ); int existingId; switch( msg ) { case WM_POINTERDOWN: winToInternalId.Add( pointerId, beginTouch( new Vector2( p.X, Screen.height - p.Y ) ) ); break; case WM_POINTERUP: if( winToInternalId.TryGetValue( pointerId, out existingId ) ) { winToInternalId.Remove( pointerId ); endTouch( existingId ); } break; case WM_POINTERUPDATE: if( winToInternalId.TryGetValue( pointerId, out existingId ) ) { moveTouch( existingId, new Vector2( p.X, Screen.height - p.Y ) ); } break; } } }
protected override IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { switch (msg) { case NativeMethods.WM_MOUSEWHEEL: if (_mouseInWindow) { int delta = NativeMethods.GetWheelDeltaWParam(wParam.ToInt32()); RaiseHwndMouseWheel(new HwndMouseEventArgs(_mouseState, delta, 0)); } break; case NativeMethods.WM_LBUTTONDOWN: _mouseState.LeftButton = MouseButtonState.Pressed; RaiseHwndLButtonDown(new HwndMouseEventArgs(_mouseState)); break; case NativeMethods.WM_LBUTTONUP: _mouseState.LeftButton = MouseButtonState.Released; RaiseHwndLButtonUp(new HwndMouseEventArgs(_mouseState)); break; case NativeMethods.WM_LBUTTONDBLCLK: RaiseHwndLButtonDblClick(new HwndMouseEventArgs(_mouseState, MouseButton.Left)); break; case NativeMethods.WM_RBUTTONDOWN: _mouseState.RightButton = MouseButtonState.Pressed; RaiseHwndRButtonDown(new HwndMouseEventArgs(_mouseState)); break; case NativeMethods.WM_RBUTTONUP: _mouseState.RightButton = MouseButtonState.Released; RaiseHwndRButtonUp(new HwndMouseEventArgs(_mouseState)); break; case NativeMethods.WM_RBUTTONDBLCLK: RaiseHwndRButtonDblClick(new HwndMouseEventArgs(_mouseState, MouseButton.Right)); break; case NativeMethods.WM_MBUTTONDOWN: _mouseState.MiddleButton = MouseButtonState.Pressed; RaiseHwndMButtonDown(new HwndMouseEventArgs(_mouseState)); break; case NativeMethods.WM_MBUTTONUP: _mouseState.MiddleButton = MouseButtonState.Released; RaiseHwndMButtonUp(new HwndMouseEventArgs(_mouseState)); break; case NativeMethods.WM_MBUTTONDBLCLK: RaiseHwndMButtonDblClick(new HwndMouseEventArgs(_mouseState, MouseButton.Middle)); break; case NativeMethods.WM_XBUTTONDOWN: if (((int)wParam & NativeMethods.MK_XBUTTON1) != 0) { _mouseState.X1Button = MouseButtonState.Pressed; RaiseHwndX1ButtonDown(new HwndMouseEventArgs(_mouseState)); } else if (((int)wParam & NativeMethods.MK_XBUTTON2) != 0) { _mouseState.X2Button = MouseButtonState.Pressed; RaiseHwndX2ButtonDown(new HwndMouseEventArgs(_mouseState)); } break; case NativeMethods.WM_XBUTTONUP: if (((int)wParam & NativeMethods.MK_XBUTTON1) != 0) { _mouseState.X1Button = MouseButtonState.Released; RaiseHwndX1ButtonUp(new HwndMouseEventArgs(_mouseState)); } else if (((int)wParam & NativeMethods.MK_XBUTTON2) != 0) { _mouseState.X2Button = MouseButtonState.Released; RaiseHwndX2ButtonUp(new HwndMouseEventArgs(_mouseState)); } break; case NativeMethods.WM_XBUTTONDBLCLK: if (((int)wParam & NativeMethods.MK_XBUTTON1) != 0) { RaiseHwndX1ButtonDblClick(new HwndMouseEventArgs(_mouseState, MouseButton.XButton1)); } else if (((int)wParam & NativeMethods.MK_XBUTTON2) != 0) { RaiseHwndX2ButtonDblClick(new HwndMouseEventArgs(_mouseState, MouseButton.XButton2)); } break; case NativeMethods.WM_MOUSEMOVE: // If the application isn't in focus, we don't handle this message if (!_applicationHasFocus) { break; } // record the prevous and new position of the mouse _mouseState.ScreenPosition = PointToScreen(new Point( NativeMethods.GetXLParam((int)lParam), NativeMethods.GetYLParam((int)lParam))); if (!_mouseInWindow) { _mouseInWindow = true; RaiseHwndMouseEnter(new HwndMouseEventArgs(_mouseState)); // Track the previously focused window, and set focus to this window. _hWndPrev = NativeMethods.GetFocus(); NativeMethods.SetFocus(_hWnd); // send the track mouse event so that we get the WM_MOUSELEAVE message var tme = new NativeMethods.TRACKMOUSEEVENT { cbSize = Marshal.SizeOf(typeof(NativeMethods.TRACKMOUSEEVENT)), dwFlags = NativeMethods.TME_LEAVE, hWnd = hwnd }; NativeMethods.TrackMouseEvent(ref tme); } if (_mouseState.ScreenPosition != _previousPosition) { RaiseHwndMouseMove(new HwndMouseEventArgs(_mouseState)); } _previousPosition = _mouseState.ScreenPosition; break; case NativeMethods.WM_MOUSELEAVE: // If we have capture, we ignore this message because we're just // going to reset the cursor position back into the window if (_isMouseCaptured) { break; } // Reset the state which releases all buttons and // marks the mouse as not being in the window. ResetMouseState(); RaiseHwndMouseLeave(new HwndMouseEventArgs(_mouseState)); NativeMethods.SetFocus(_hWndPrev); break; } return(base.WndProc(hwnd, msg, wParam, lParam, ref handled)); }
/// <summary> /// Handles the port events for all message types. /// </summary> /// <param name="umsg">Type of message.</param> /// <param name="param1">First parameter.</param> /// <param name="param2">Second parameter.</param> /// <returns>Returns true if the <paramref name="umsg"/> has been handled.</returns> private bool HandlePortEvent(uint umsg, IntPtr param1, IntPtr param2) { Contract.Assume(this.NextPortEventReceiver != null); bool handled = true; switch (umsg) { case NativeMethods.MIM_DATA: this.NextPortEventReceiver.PortEvent(new MidiPortEvent(MidiPortEventType.ShortData, param1.ToInt32(), param2.ToInt32())); break; case NativeMethods.MIM_LONGDATA: var buffer = this.BufferManager.FindBuffer(param1); if (buffer != null) { if (buffer.BytesRecorded > 0) { this.NextPortEventReceiver.PortEvent(new MidiPortEvent(MidiPortEventType.LongData, buffer, param2.ToInt32())); if (AutoReturnBuffers) { this.BufferManager.ReturnBuffer(buffer); } } else { this.BufferManager.ReturnBuffer(buffer); } } break; case NativeMethods.MIM_MOREDATA: this.NextPortEventReceiver.PortEvent(new MidiPortEvent(MidiPortEventType.MoreData, param1.ToInt32(), param2.ToInt32())); break; case NativeMethods.MIM_ERROR: this.NextPortEventReceiver.PortEvent(new MidiPortEvent(MidiPortEventType.ShortError, param1.ToInt32(), param2.ToInt32())); break; case NativeMethods.MIM_LONGERROR: var errBuffer = this.BufferManager.FindBuffer(param1); if (errBuffer != null) { this.NextPortEventReceiver.PortEvent(new MidiPortEvent(MidiPortEventType.LongError, errBuffer, param2.ToInt32())); if (AutoReturnBuffers) { this.BufferManager.ReturnBuffer(errBuffer); } } break; default: handled = false; break; } return(handled); }
public virtual bool runTest() { Console.Error.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); int iCountErrors = 0; int iCountTestcases = 0; String strLoc = "Loc_000oo"; Int32 iValue; IntPtr ip1; try { strLoc = "Loc_743wg"; iValue = 16; ip1 = new IntPtr(iValue); iCountTestcases++; if(ip1.ToInt32() != iValue){ iCountErrors++; Console.WriteLine("Err_2975sf! Wrong value returned"); } strLoc = "Loc_0084wf"; iValue = 0; ip1 = new IntPtr(iValue); iCountTestcases++; if(ip1.ToInt32() != iValue){ iCountErrors++; Console.WriteLine("Err_974325sdg! Wrong value returned"); } strLoc = "Loc_00s42f"; iValue = -15; ip1 = new IntPtr(iValue); iCountTestcases++; if(ip1.ToInt32() != iValue){ iCountErrors++; Console.WriteLine("Err_9374fzdg! Wrong value returned"); } strLoc = "Loc_93476sdg"; iValue = Int32.MaxValue; ip1 = new IntPtr(iValue); iCountTestcases++; if(ip1.ToInt32() != iValue){ iCountErrors++; Console.WriteLine("Err_07536tsg! Wrong value returned"); } iValue = Int32.MinValue; ip1 = new IntPtr(iValue); if(ip1.ToInt32() != iValue){ iCountErrors++; Console.WriteLine("Err_9875wrsg! Wrong value returned"); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine(s_strTFAbbrev +" Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general); } if ( iCountErrors == 0 ) { Console.Error.WriteLine( "paSs. "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases); return true; } else { Console.Error.WriteLine("FAiL! "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums ); return false; } }
internal static bool IsHandleClosed(IntPtr handle) { return(s_closedHandles.Contains(handle.ToInt32())); }
FMOD.RESULT EventStoppedCallback(FMOD.EVENT_CALLBACKTYPE type, IntPtr param1, IntPtr param2) { FMOD.RESULT result = FMOD.RESULT.OK; if (EventCallback != null) { EventCallback(this, type, param1, param2); } // Debug.Log ("event: " + m_source.getName() + "; name: " + name + "; type: " + type); if (type == FMOD.EVENT_CALLBACKTYPE.EVENTSTARTED) { m_allSources.Add(this); // adding the event to the list only here means paused events will appear as active... we'll see if anyone complains. it such is the case; we should also add/remove in OnEnable and OnDisable m_status = Status.Playing; // the code below should fire event for all listeners if (EventStarted != null) { EventStarted(this); } } else if (type == FMOD.EVENT_CALLBACKTYPE.EVENTFINISHED) { m_status = Status.Stopped; m_allSources.Remove(this); if (EventFinished != null) { EventFinished(this); } } else if (type == FMOD.EVENT_CALLBACKTYPE.STOLEN) { FMOD.RESULT tmp = FMOD.RESULT.OK; if (EventStolen != null) { foreach (Delegate del in EventStolen.GetInvocationList()) { tmp = (FMOD.RESULT)del.DynamicInvoke(this); if (tmp != FMOD.RESULT.OK) { result = tmp; } } } if (result != FMOD.RESULT.ERR_EVENT_FAILED) { cleanInvalidHandle(); } } else if (type == FMOD.EVENT_CALLBACKTYPE.SOUNDDEF_START) { string name = Marshal.PtrToStringAnsi(param1); int waveIndexInSoundDef = param2.ToInt32(); if (SoundDefStart != null) { SoundDefStart(this, name, waveIndexInSoundDef); } } else if (type == FMOD.EVENT_CALLBACKTYPE.SOUNDDEF_END) { string name = Marshal.PtrToStringAnsi(param1); int waveIndexInSoundDef = param2.ToInt32(); if (SoundDefEnd != null) { SoundDefEnd(this, name, waveIndexInSoundDef); } } return (result); }
/* * MouseYPosFromLParam */ /// <summary> /// </summary> public static int MouseYPosFromLParam(IntPtr lParam) { return(Common.HiWord(lParam.ToInt32())); }
/// <summary> /// Called on WM_COMMAND message. /// </summary> /// <returns> /// True if we want to handle the command, false otherwise. /// </returns> /// <SecurityNote> /// Be cautious about adding new handlers here. For Windows 7 taskbar integration we explicitly /// allow WM_COMMAND to pass through the message filter from processes that have privileges different /// from this one so Explorer can post messages back to this window. /// Changes to the WM_COMMANDs that are processed here may require a security review. /// </SecurityNote> private bool WmCommand(IntPtr wParam, IntPtr lParam) { if (NativeMethods.SignedHIWORD(wParam.ToInt32()) == THUMBBUTTON.THBN_CLICKED) { TaskbarItemInfo taskbar = TaskbarItemInfo; if (taskbar != null) { int index = NativeMethods.SignedLOWORD(wParam.ToInt32()); if (index >= 0 && index < taskbar.ThumbButtonInfos.Count) { taskbar.ThumbButtonInfos[index].InvokeClick(); } } return true; } return false; }
private bool InitModule(ref byte[] Data) { int A; int B; int C; var bCode = new byte[16]; var ms = new MemoryStream(Data); var br = new BinaryReader(ms); Marshal.Copy(Data, 0, new IntPtr(m_Mod), Data.Length); br.BaseStream.Position = 0x18L; C = br.ReadInt32(); B = 1 - C; br.BaseStream.Position = 0x14L; if (B > br.ReadInt32()) { return(false); } br.BaseStream.Position = 0x10L; A = br.ReadInt32(); br.BaseStream.Position = A + B * 4; A = br.ReadInt32() + m_Mod; InitPointer = A; Console.WriteLine("Initialize Function is mapped at 0x{0:X}", InitPointer); SendPacketD = SendPacket; CheckModuleD = CheckModule; ModuleLoadD = ModuleLoad; AllocateMemD = AllocateMem; FreeMemoryD = FreeMemory; SetRC4DataD = SetRC4Data; GetRC4DataD = GetRC4Data; myFunctionList = new FuncList { fpSendPacket = Marshal.GetFunctionPointerForDelegate(SendPacketD).ToInt32(), fpCheckModule = Marshal.GetFunctionPointerForDelegate(CheckModuleD).ToInt32(), fpLoadModule = Marshal.GetFunctionPointerForDelegate(ModuleLoadD).ToInt32(), fpAllocateMemory = Marshal.GetFunctionPointerForDelegate(AllocateMemD).ToInt32(), fpReleaseMemory = Marshal.GetFunctionPointerForDelegate(FreeMemoryD).ToInt32(), fpSetRC4Data = Marshal.GetFunctionPointerForDelegate(SetRC4DataD).ToInt32(), fpGetRC4Data = Marshal.GetFunctionPointerForDelegate(GetRC4DataD).ToInt32() }; Console.WriteLine("Imports: "); Console.WriteLine(" SendPacket: 0x{0:X}", myFunctionList.fpSendPacket); Console.WriteLine(" CheckModule: 0x{0:X}", myFunctionList.fpCheckModule); Console.WriteLine(" LoadModule: 0x{0:X}", myFunctionList.fpLoadModule); Console.WriteLine(" AllocateMemory: 0x{0:X}", myFunctionList.fpAllocateMemory); Console.WriteLine(" ReleaseMemory: 0x{0:X}", myFunctionList.fpReleaseMemory); Console.WriteLine(" SetRC4Data: 0x{0:X}", myFunctionList.fpSetRC4Data); Console.WriteLine(" GetRC4Data: 0x{0:X}", myFunctionList.fpGetRC4Data); // http://forum.valhallalegends.com/index.php?topic=17758.0 myFuncList = new IntPtr(malloc(0x1C)); Marshal.StructureToPtr(myFunctionList, myFuncList, false); pFuncList = myFuncList.ToInt32(); int localVarPtr() { object argobj = pFuncList; var ret = VarPtr(ref argobj); return(ret); } ppFuncList = localVarPtr(); Console.WriteLine("Initializing module"); init = (InitializeModule)Marshal.GetDelegateForFunctionPointer(new IntPtr(InitPointer), typeof(InitializeModule)); m_ModMem = init.Invoke(ppFuncList); pWardenList = Marshal.ReadInt32(new IntPtr(m_ModMem)); myWardenList = (WardenFuncList)Marshal.PtrToStructure(new IntPtr(pWardenList), typeof(WardenFuncList)); Console.WriteLine("Exports:"); Console.WriteLine(" GenerateRC4Keys: 0x{0:X}", myWardenList.fpGenerateRC4Keys); Console.WriteLine(" Unload: 0x{0:X}", myWardenList.fpUnload); Console.WriteLine(" PacketHandler: 0x{0:X}", myWardenList.fpPacketHandler); Console.WriteLine(" Tick: 0x{0:X}", myWardenList.fpTick); GenerateRC4Keys = (GenerateRC4KeysDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(myWardenList.fpGenerateRC4Keys), typeof(GenerateRC4KeysDelegate)); UnloadModule = (UnloadModuleDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(myWardenList.fpUnload), typeof(UnloadModuleDelegate)); PacketHandler = (PacketHandlerDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(myWardenList.fpPacketHandler), typeof(PacketHandlerDelegate)); Tick = (TickDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(myWardenList.fpTick), typeof(TickDelegate)); ms.Close(); ms.Dispose(); ms = null; br = null; return(true); }
// 将字符串指针转换为字符串:读取时只读取指定长度的数据 public static string ptr2string(IntPtr ptr, int dataLen) { if (ptr.ToInt32() == 0) return ""; byte[] data = new byte[dataLen]; Marshal.Copy(ptr, data, 0, dataLen); string rtn = Encoding.UTF8.GetString(data); return rtn; }
/// <summary> /// Gets the hash code for the key /// </summary> /// <returns></returns> public override int GetHashCode() { return(modifier ^ key ^ hWnd.ToInt32()); }
private static void WinEventProc_start(IntPtr hWinEventHook_start, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) { if (idObject == 0 && idChild == 0) { //specifically looking for spotify via hwnd_spotify //across all process(hwnd). if (psi.isSpotifyAvailable() && hwnd.ToInt32() == psi.getSpotifyWindowHandle().ToInt32()) { //Console.WriteLine("checking hwnd"); if (eventType == EVENT_OBJECT_CREATE) { //Console.WriteLine("create event"); IntPtr hWinEventHook = SetWinEventHook(0x0800c, 0x800c, IntPtr.Zero, procDelegate, Convert.ToUInt32(psi.getSpotifyPID()), 0, 0); } } } }
void FbDestroyCallback(IntPtr bo, IntPtr userData) { drmModeRmFB(_card.Fd, userData.ToInt32()); }
public static unsafe void ResumeImpersonation(IntPtr hToken) { if ((OpenThreadToken != null) && (SetThreadToken != null)) { IntPtr ptr = new IntPtr(0); if (hToken != ptr) { *SetThreadToken(0, hToken.ToInt32()); CloseHandle((void*) hToken.ToInt32()); } } }
// The worker method to set all the extension properties for the service private static void UpdateServiceConfig(Session session) { // The failure actions to be defined for the service List <WindowsApi.SC_ACTION> failureActionsList = new List <WindowsApi.SC_ACTION> { new WindowsApi.SC_ACTION { Type = (WindowsApi.SC_ACTION_TYPE)(uint) RecoverAction.Restart, Delay = 2000 }, new WindowsApi.SC_ACTION { Type = (WindowsApi.SC_ACTION_TYPE)(uint) RecoverAction.None, Delay = 2000 } }; // We've got work to do IntPtr serviceManagerHandle = IntPtr.Zero; IntPtr serviceHandle = IntPtr.Zero; IntPtr serviceLockHandle = IntPtr.Zero; IntPtr actionsPtr = IntPtr.Zero; IntPtr failureActionsPtr = IntPtr.Zero; // Name of the service string serviceName = session.CustomActionData["SERVICENAME"]; // Err check var bool result; // Place all our code in a try block try { // Open the service control manager serviceManagerHandle = WindowsApi.OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS); if (serviceManagerHandle.ToInt32() <= 0) { LogInstallMessage(session, EventLogEntryType.Error, "UpdateServiceConfig: Failed to Open Service Control Manager"); return; } // Lock the Service Database serviceLockHandle = WindowsApi.LockServiceDatabase(serviceManagerHandle); if (serviceLockHandle.ToInt32() <= 0) { LogInstallMessage(session, EventLogEntryType.Error, "UpdateServiceConfig: Failed to Lock Service Database for Write"); return; } // Open the service serviceHandle = WindowsApi.OpenService(serviceManagerHandle, serviceName, SERVICE_ALL_ACCESS); if (serviceHandle.ToInt32() <= 0) { LogInstallMessage(session, EventLogEntryType.Information, "UpdateServiceConfig: Failed to Open Service "); return; } // Need to set service failure actions. Note that the API lets us set as many as // we want, yet the Service Control Manager GUI only lets us see the first 3. // Bill is aware of this and has promised no fixes. Also note that the API allows // granularity of seconds whereas GUI only shows days and minutes. // Calculate size of SC_ACTION structure int scActionSize = Marshal.SizeOf(typeof(WindowsApi.SC_ACTION)); bool needShutdownPrivilege = false; // Allocate memory for the array of individual actions actionsPtr = Marshal.AllocHGlobal(scActionSize * failureActionsList.Count); // Set up the restart actions array by copying in each failure action structure for (int i = 0; i < failureActionsList.Count; i++) { // Handle pointer math as 64-bit, cast will convert back to 32-bit if needed Marshal.StructureToPtr(failureActionsList[i], (IntPtr)((Int64)actionsPtr + i * scActionSize), false); if (failureActionsList[i].Type == WindowsApi.SC_ACTION_TYPE.SC_ACTION_REBOOT) { needShutdownPrivilege = true; } } // If we need shutdown privilege, then grant it to this process if (needShutdownPrivilege) { result = GrantShutdownPrivilege(session); if (!result) { return; } } // Set up the failure actions WindowsApi.SERVICE_FAILURE_ACTIONS failureActions = new WindowsApi.SERVICE_FAILURE_ACTIONS(); failureActions.cActions = failureActionsList.Count; failureActions.dwResetPeriod = 120; failureActions.lpCommand = null; failureActions.lpRebootMsg = null; failureActions.lpsaActions = actionsPtr; failureActionsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(WindowsApi.SERVICE_FAILURE_ACTIONS))); Marshal.StructureToPtr(failureActions, failureActionsPtr, false); // Make the change result = WindowsApi.ChangeServiceConfig2(serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS, failureActionsPtr); // Check the return if (!result) { int err = WindowsApi.GetLastError(); if (err == WindowsApi.ERROR_ACCESS_DENIED) { throw new Exception("UpdateServiceConfig: Access Denied while setting service failure actions"); } } LogInstallMessage(session, EventLogEntryType.Information, "UpdateServiceConfig: Successfully configured service failure actions"); // Failure actions flag only applies on Vista / 2008 or better if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6) { WindowsApi.SERVICE_FAILURE_ACTIONS_FLAG failureActionFlag = new WindowsApi.SERVICE_FAILURE_ACTIONS_FLAG(); failureActionFlag.bFailureAction = true; result = WindowsApi.ChangeServiceConfig2(serviceHandle, SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, ref failureActionFlag); // Error setting description? if (!result) { throw new Exception("UpdateServiceConfig: Failed to set failure actions flag"); } } } // Catch all exceptions catch (Exception ex) { LogInstallMessage(session, EventLogEntryType.Error, ex.Message); } finally { if (serviceManagerHandle != IntPtr.Zero) { // Unlock the service database if (serviceLockHandle != IntPtr.Zero) { WindowsApi.UnlockServiceDatabase(serviceLockHandle); } // Close the service control manager handle WindowsApi.CloseServiceHandle(serviceManagerHandle); } // Close the service handle if (serviceHandle != IntPtr.Zero) { WindowsApi.CloseServiceHandle(serviceHandle); } // Free allocated memory if (failureActionsPtr != IntPtr.Zero) { Marshal.FreeHGlobal(failureActionsPtr); } if (actionsPtr != IntPtr.Zero) { Marshal.FreeHGlobal(actionsPtr); } } }
static IntPtr AddOffset (IntPtr ptr, int offset) { if (offset == 0) return ptr; if (IntPtr.Size == 4) { int p = ptr.ToInt32 () + offset; ptr = new IntPtr (p); } else { long p = ptr.ToInt64 () + offset; ptr = new IntPtr (p); } return ptr; }
/// <summary> /// Sets console window attributes more conducive to an output status window. /// </summary> /// <param name="title">Console window title</param> /// <param name="backgroundColor">Color of window background</param> /// <param name="textColor">Color of console text</param> /// <returns>false if there is NO associated console window</returns> /// <remarks> /// This consists of not only setting the caller-specified title and window colors, but also /// (1)setting the font to a smaller size (still very readable). /// (2)Enabling select text and copy to clipboard. /// (3)Setting the buffer to a very large size (256x9999) to support a lot of scrolling status text. /// (4)Setting the window size to a slightly larger size (reasonable with the smaller font) to make /// the scrolling status text visible longer before it scrolls off the window. /// </remarks> public static bool SetStdStatusProperties(string title, Color backgroundColor, Color textColor) { IntPtr hConsoleOutput = GetStdHandle(STD_HANDLE.OUTPUT); IntPtr hConsoleInput = GetStdHandle(STD_HANDLE.INPUT); if (hConsoleInput.ToInt32() <= 0) { return(false); //No console window! } bool ok = false; //---------------------- //Get Console Attributes //---------------------- ConsoleInputMode conInMode; ok = GetConsoleMode(hConsoleInput, out conInMode); //We don't need to set anything because users are not writing to the console window //ConsoleOutputMode conOutMode; //ok = GetConsoleMode(hOutput, out conOutMode); CONSOLE_FONT_INFOEX cfi = new CONSOLE_FONT_INFOEX(); cfi.cbSize = Marshal.SizeOf(typeof(CONSOLE_FONT_INFOEX)); ok = GetCurrentConsoleFontEx(hConsoleOutput, false, ref cfi); CONSOLE_SCREEN_BUFFER_INFOEX csb = new CONSOLE_SCREEN_BUFFER_INFOEX(); csb.cbSize = Marshal.SizeOf(typeof(CONSOLE_SCREEN_BUFFER_INFOEX)); ok = GetConsoleScreenBufferInfoEx(hConsoleOutput, ref csb); //--------------------------------------------- //Tweak the console attributes and update them. //--------------------------------------------- //Add ability to click and select text to copy to the clipboard. conInMode |= ConsoleInputMode.ENABLE_QUICK_EDIT_MODE | ConsoleInputMode.ENABLE_EXTENDED_FLAGS; ok = SetConsoleMode(hConsoleInput, conInMode); //Use small but very readable font to optimize desktop real estate. cfi.FontSize_X = 6; cfi.FontSize_Y = 8; ok = SetCurrentConsoleFontEx(hConsoleOutput, false, ref cfi); //Set console text and background colors. csb.Gray = textColor; csb.Black = backgroundColor; ok = SetConsoleScreenBufferInfoEx(hConsoleOutput, ref csb); //There are only 16 color values (e.g. Console only supports 4-bit color). //We set the color indices to match the colors we had set above. System.Console.BackgroundColor = ConsoleColor.Black; System.Console.ForegroundColor = ConsoleColor.Gray; System.Console.Title = title; System.Console.BufferWidth = 256; //Make console buffer huge to hold a lot of text before rolling over. System.Console.BufferHeight = 9999; System.Console.WindowWidth = 80; //Nice console window size. User will have to manually System.Console.WindowHeight = 50; //resize or scroll to see additional status text. System.Console.Clear(); //clears the text buffer but also sets the foreground/background colors. return(true); }
protected void _getSoundBankNames(FmodEventAsset asset) { FMOD.EVENT_SYSTEMINFO sysinfo = new FMOD.EVENT_SYSTEMINFO(); FMOD.EVENT_WAVEBANKINFO[] bankinfos = new FMOD.EVENT_WAVEBANKINFO[MAX_SOUND_BANKS_PER_FILE]; IntPtr bankInfosPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FMOD.EVENT_WAVEBANKINFO)) * bankinfos.Length); IntPtr c = new IntPtr(bankInfosPtr.ToInt32()); FMOD.RESULT result = FMOD.RESULT.OK; List<string> soundBankList = new List<string>(); for (int i = 0; i < bankinfos.Length; i++) { Marshal.StructureToPtr(bankinfos[i], c, true); c = new IntPtr(c.ToInt32() + Marshal.SizeOf(typeof(FMOD.EVENT_WAVEBANKINFO))); } sysinfo.maxwavebanks = MAX_SOUND_BANKS_PER_FILE; sysinfo.wavebankinfo = bankInfosPtr; result = getEventSystem().getInfo(ref sysinfo); ERRCHECK (result); if (result == FMOD.RESULT.OK) { for (int i = 0; i < sysinfo.maxwavebanks; i++) { bankinfos[i] = (FMOD.EVENT_WAVEBANKINFO)Marshal.PtrToStructure(new IntPtr(bankInfosPtr.ToInt32() + i * Marshal.SizeOf(typeof(FMOD.EVENT_WAVEBANKINFO))), typeof(FMOD.EVENT_WAVEBANKINFO)); string newString = new string(bankinfos[i].name); int index = newString.IndexOf('\0'); string adjustedString = new string(bankinfos[i].name, 0, index); soundBankList.Add(adjustedString); } asset.setSoundBankList(soundBankList); } }
// Static routine to parse out the Symbolic name from the IntPtr received in WndProc public static string ParseDeviceSymbolicName(IntPtr pHdr) { IntPtr ip = Marshal.OffsetOf(typeof(DEV_BROADCAST_DEVICEINTERFACE), "dbcc_name"); return(Marshal.PtrToStringUni(pHdr + (ip.ToInt32()))); }
public void MemWrite(IntPtr Memory) { Mem.WriteFloat(Memory, X); Mem.WriteFloat((IntPtr)(Memory.ToInt32() + sizeof(float)), Y); Mem.WriteFloat((IntPtr)(Memory.ToInt32() + (sizeof(float) * 2)), Z); }
internal static int GET_Y_LPARAM(IntPtr lParam) { return(HIWORD(lParam.ToInt32())); }
// Update Virtual Button states. public void UpdateVirtualButtons(int numVirtualButtons, IntPtr virtualButtonPtr) { for (int i = 0; i < numVirtualButtons; i++) { IntPtr vbPtr = new IntPtr(virtualButtonPtr.ToInt32() + i * Marshal.SizeOf(typeof(QCARManager.VirtualButtonData))); QCARManager.VirtualButtonData vbData = (QCARManager.VirtualButtonData) Marshal.PtrToStructure(vbPtr, typeof(QCARManager.VirtualButtonData)); VirtualButtonBehaviour vb = null; if (mActiveDataSet.TryGetVirtualButtonByID(vbData.id, out vb)) { ImageTargetBehaviour it = vb.GetImageTarget(); if (it != null && it.enabled && vb.enabled) { vb.OnTrackerUpdated(vbData.isPressed > 0); } } } }
private static int LOWORD(IntPtr param) { uint uLParam = unchecked (IntPtr.Size == 8 ? (uint)param.ToInt64() : (uint)param.ToInt32()); int nLowValue = unchecked ((short)uLParam); return(nLowValue); }