/// <summary> /// Gets the icon as an <see cref="ImageSource"/> for the specified path. /// </summary> /// <param name="path">The path.</param> /// <param name="info">The shell file info.</param> /// <returns>The icon as an <see cref="ImageSource"/> for the specified path.</returns> public static ImageSource GetImageSource(string path, out Win32.SHFILEINFO info) { info = new Win32.SHFILEINFO(); int attr; if (Directory.Exists(path)) attr = (int)Win32.FILE_ATTRIBUTE_DIRECTORY; else if (File.Exists(path)) attr = (int)Win32.FILE_ATTRIBUTE_NORMAL; else if (path.Length == 3) // drive not ready attr = (int)Win32.FILE_ATTRIBUTE_DIRECTORY; else return null; Win32.SHGetFileInfo(path, attr, out info, (uint)Marshal.SizeOf(typeof(Win32.SHFILEINFO)), Win32.SHGFI_DISPLAYNAME | Win32.SHGFI_ICON | Win32.SHGFI_TYPENAME | Win32.SHGFI_SMALLICON | Win32.SHGFI_USEFILEATTRIBUTES); ImageSource img = null; if (info.hIcon != IntPtr.Zero) { using (Icon icon = Icon.FromHandle(info.hIcon)) { img = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, new Int32Rect(0, 0, icon.Width, icon.Height), BitmapSizeOptions.FromEmptyOptions()); } Win32.DestroyIcon(info.hIcon); } return img; }
public Monitor(Win32.DISPLAY_DEVICE device, Win32.DEVMODE currentDisplaySettings, List<Win32.DEVMODE> availableDisplaySettings) { Device = device; AvailableDisplaySettings = availableDisplaySettings; CurrentDisplaySettings = currentDisplaySettings; IsPrimary = CurrentDisplaySettings.dmPositionX == 0 && CurrentDisplaySettings.dmPositionY == 0; }
bool GetPreferences(string section, out Win32.RECT rect, out long style, out long exStyle) { rect = new Win32.RECT(); style = 0; exStyle = 0; if (!Preferences.HasSection(section)) { return false; } string[] keys = { "rectLeft", "rectTop", "rectRight", "rectBottom", "style", "exStyle" }; foreach (string key in keys) { if (!Preferences[section].HasKey(key)) { return false; } } if (!int.TryParse(Preferences[section]["rectLeft"].Value, out rect.Left)) { return false; } if (!int.TryParse(Preferences[section]["rectTop"].Value, out rect.Top)) { return false; } if (!int.TryParse(Preferences[section]["rectRight"].Value, out rect.Right)) { return false; } if (!int.TryParse(Preferences[section]["rectBottom"].Value, out rect.Bottom)) { return false; } if (!long.TryParse(Preferences[section]["style"].Value, out style)) { return false; } if (!long.TryParse(Preferences[section]["exStyle"].Value, out exStyle)) { return false; } return true; }
private Tree CaptureWindow(IntPtr hwnd, Win32.WINDOWINFO windowinfo, bool usePrintWindow, bool fixedSize = false) { BoundingBox windowRect = new BoundingBox(windowinfo.rcWindow.left, windowinfo.rcWindow.top, windowinfo.rcWindow.right - windowinfo.rcWindow.left + 1, windowinfo.rcWindow.bottom - windowinfo.rcWindow.top + 1); var attributes = GetWindowAttributes(hwnd, windowinfo); if (windowRect.Width > 0 && windowRect.Height > 0) { System.Drawing.Bitmap bmp; int width = windowRect.Width; int height = windowRect.Height; if(fixedSize) { width = (int)System.Windows.SystemParameters.VirtualScreenWidth; height = (int)System.Windows.SystemParameters.VirtualScreenHeight; } if (!usePrintWindow) bmp = GetBitmapFromScreen(hwnd, null, width, height); else bmp = GetBitmapFromPrintWindow(hwnd, null, width, height); Tree window = _bitmapToTree.GetScreenshotAndCreateTree(windowRect.Width, windowRect.Height, bmp, attributes); //_pool.ReturnInstance(bmp); return window; } return null; }
// Methods public ColorOperation() { this.mouseAreaControl = null; this.translatePath = new GraphicsPath(); this.scalePath = new GraphicsPath(); this.rotatePath = new GraphicsPath(); this.equalPath = new GraphicsPath(); this.skewxPath = new GraphicsPath(); this.skewyPath = new GraphicsPath(); this.anglescalePath = new GraphicsPath(); this.vscalPath = new GraphicsPath(); this.controlPoints = null; this.reversePath = new GraphicsPath(); this.startPoint = PointF.Empty; this.win32 = new Win32(); this.ratiomatrix = new Matrix(); this.graphMatrix = new Matrix(); this.selectMatrix = new Matrix(); this.gradientMatrix = new Matrix(); this.gradientPath = new GraphicsPath(); this.gradientheight = 1f; this.centerPoint = PointF.Empty; this.gradientstr = string.Empty; this.colorpickerstr = string.Empty; this.gradientstr = DrawAreaConfig.GetLabelForName("gradienttransform").Trim(); this.colorpickerstr = DrawAreaConfig.GetLabelForName("colorpicker").Trim(); }
static bool HandleCtrl(Win32.CtrlTypes type) { var name = Enum.GetName(type.GetType(), type); Console.WriteLine("\nExiting due to {0} event from system!\n", name); if (f != null) f.TerminateBots(); return true; }
public static bool Click(Win32.Point point) { if (bshandle == IntPtr.Zero) bshandle = GetBlueStackWindowHandle(); if (bshandle == IntPtr.Zero) return false; MouseHelper.ClickOnPoint(bshandle, point); return true; }
// Methods public ViewOperation() { this.mouseAreaControl = null; this.startPoint = Point.Empty; this.oldleft = 0f; this.oldtop = 0f; this.reversePath =new GraphicsPath(); this.win32 = new Win32(); }
bool SetPreferences(string section, Win32.RECT rect, long style, long exStyle) { Preferences[section]["rectLeft"].Value = rect.Left.ToString(); Preferences[section]["rectTop"].Value = rect.Top.ToString(); Preferences[section]["rectRight"].Value = rect.Right.ToString(); Preferences[section]["rectBottom"].Value = rect.Bottom.ToString(); Preferences[section]["style"].Value = style.ToString(); Preferences[section]["exStyle"].Value = exStyle.ToString(); return true; }
public static int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref Win32.MARGINS margins) { IntPtr hModule = Win32.LoadLibrary("dwmapi"); if (hModule == IntPtr.Zero) return 0; IntPtr procAddress = Win32.GetProcAddress(hModule, "DwmExtendFrameIntoClientArea"); if (procAddress == IntPtr.Zero) return 0; else return ((Win32.DwmExtendFrameIntoClientAreaDelegate) Marshal.GetDelegateForFunctionPointer(procAddress, typeof (Win32.DwmExtendFrameIntoClientAreaDelegate)))(hwnd, ref margins); }
internal DrawOperation(MouseArea mousecontrol) : this() { this.mouseAreaControl = mousecontrol; this.win32 = this.mouseAreaControl.win32; this.openFileDialog1 = new OpenFileDialog(); string text1 = DrawAreaConfig.GetLabelForName("filefilter").Trim(); this.openFileDialog1.Filter = text1; this.openFileDialog1.Title = DrawAreaConfig.GetLabelForName("imagedialog").Trim(); this.openFileDialog1.FileOk += new CancelEventHandler(this.openFileDialog1_FileOk); }
private IntPtr EnumWindowByName(Win32.EnumWindowsProc filter) { IntPtr WindowHwnd = IntPtr.Zero; Win32.EnumWindows(delegate(IntPtr hwnd, IntPtr lparam) { if (filter(hwnd, lparam)) { WindowHwnd = hwnd; return false; } return true; }, IntPtr.Zero); return WindowHwnd; }
// Methods public DrawOperation() { this.mouseAreaControl = null; this.win32 = new Win32(); this.tempPath = new GraphicsPath(); this.drawPath = null; this.showdialog = false; this.filename = string.Empty; this.haveTextActive = false; this.startPoint = Point.Empty; this.mouseDown = false; this.reversePath = new GraphicsPath(); this.first = true; this.list = new ArrayList(); this.tooltips = new Hashtable(); this.finish = false; this.redPath =new GraphicsPath(); }
/// <summary> /// ������ /// </summary> /// <param name="mc"></param> public DistanceOperation(MouseArea mc) { this.reversePath = new GraphicsPath(); this.graph = null; this.points = new ArrayList(); this.moveindex = -1; this.startpoint = PointF.Empty; this.prePoint = PointF.Empty; this.nextPoint = PointF.Empty; this.insertindex = -1; this.tooltips = new Hashtable(0x10); this.oldpoints = string.Empty; this.mousedown = false; this.mouseAreaControl = mc; this.win32 = mc.win32; this.mouseAreaControl.DefaultCursor = SpecialCursors.MeasureCursor; this.tempPath=new GraphicsPath(); this.connectPoint=PointF.Empty; }
private IntPtr EnumChildWindowByName(IntPtr parent, Win32.EnumWindowsProc filter) { IntPtr WindowHwnd = IntPtr.Zero; Win32.EnumChildWindows(parent, delegate(IntPtr hwnd, IntPtr lparam) { if (filter(hwnd, lparam)) { WindowHwnd = hwnd; return false; } else { EnumChildWindowByName(hwnd, filter); } return true; }, IntPtr.Zero); return WindowHwnd; }
// Methods public SelectOperation() { this.mouseAreaControl = null; this.toBeSelectedGraph = null; this.toBeSelectedPath = null; this.currentMousePoint = MousePoint.None; this.reversePath = new GraphicsPath(); this.oriPath = new GraphicsPath(); this.startpoint = PointF.Empty; this.movePoint = PointF.Empty; this.selectMatrix = new Matrix(); this.totalmatrix = new Matrix(); this.controlPoint = PointF.Empty; this.selectAreaPath = new GraphicsPath(); this.win32 = new Win32(); this.AreaPoints = new ArrayList(0x10); this.ps = new PointF[8]; this.rotateindex = 0; this.selectCollection = new SvgElementCollection(); this.tooltips = new Hashtable(0x10); this.rotatepath = new GraphicsPath(); }
int Hooked(int code, IntPtr wparam, ref Win32.CWPSTRUCT cwp) { switch(code) { case 0: switch(cwp.message) { case Win32.WM_CREATE: string s = string.Empty; char[] className = new char[10]; int length = Win32.GetClassName( cwp.hwnd, className, 9 ); for( int i = 0; i < length; i++ ) s += className[i]; if( s == "#32768" ) { // System class for menu defaultWndProc = Win32.SetWindowLong( cwp.hwnd, (-4), subWndProc ); //int old = Win32.GetWindowLong( cwp.hwnd, (-20) ); //Win32.SetWindowLong2( cwp.hwnd, (-20)/*GWL_EXSTYLE=(-20)*/, 0x20/*WS_EX_TRANSPARENT=0x20*/ ); } break; } break; } return Win32.CallNextHookEx(hookHandle,code,wparam, ref cwp); }
private Dictionary<string, object> GetWindowAttributes(IntPtr hwnd, Win32.WINDOWINFO windowinfo) { Dictionary<string, object> attributes = new Dictionary<string, object>(); attributes["handle"] = hwnd; ExpensiveWindowInfo expensiveInfo; if (!_windowInfo.TryGetValue(hwnd, out expensiveInfo)) { expensiveInfo = new ExpensiveWindowInfo(Win32.GetClassName(hwnd), Win32.GetWindowText(hwnd), Win32.GetProcessPathFromWindowHandle(hwnd)); _windowInfo.Add(hwnd, expensiveInfo); } attributes["processfilename"] = expensiveInfo.ProcessFilePath; attributes["title"] = expensiveInfo.Title; attributes["classname"] = expensiveInfo.ClassName; attributes["style"] = windowinfo.dwStyle; attributes["exstyle"] = windowinfo.dwExStyle; return attributes; }
// Methods public PolyOperation(MouseArea mc) { this.mouseAreaControl = null; this.win32 = null; this.reversePath = new GraphicsPath(); this.graph = null; this.operate = PolyOperate.Draw; this.points = new PointF[0]; this.moveindex = -1; this.startpoint = PointF.Empty; this.prePoint = PointF.Empty; this.nextPoint = PointF.Empty; this.insertindex = -1; this.tooltips = new Hashtable(0x10); this.oldpoints = string.Empty; this.mousedown = false; this.AreaPoints=new ArrayList(); this.mouseAreaControl = mc; this.win32 = mc.win32; this.mouseAreaControl.PicturePanel.GraphChanged += new EventHandler(this.ChangeGraph); this.mouseAreaControl.SVGDocument.SelectCollection.OnCollectionChangedEvent += new OnCollectionChangedEventHandler(this.ChangeSelect); this.mouseAreaControl.DefaultCursor = SpecialCursors.bezierCursor; }
internal IntPtr addHook(Win32.HookingIDs hID, WinAPI.LowLevelMouseProc callback) { if (ModuleHandle == IntPtr.Zero) { using (var curProcess = Process.GetCurrentProcess()) using (var curModule = curProcess.MainModule) { IntPtr ret = WinAPI.SetWindowsHookEx((int)hID, callback, WinAPI.GetModuleHandle(curModule.ModuleName), 0); HookInfo info = new HookInfo(); info.hookID = ret; info.callback = callback; info.hID = hID; hookIDs.Add(info); return ret; } } else { IntPtr ret = WinAPI.SetWindowsHookEx((int)hID, callback, ModuleHandle, 0); HookInfo info = new HookInfo(); info.hookID = ret; info.callback = callback; info.hID = hID; hookIDs.Add(info); hookIDs.Add(info); return ret; } }
/// <summary> /// The callback for the Keyboard hook /// </summary> /// <param name="code"></param> /// <param name="wParam"></param> /// <param name="lParam"></param> /// <returns></returns> private int HookProc(int code, int wParam, ref Win32.KBDLLHOOKSTRUCT lParam) { if (code >= 0) { Key key = System.Windows.Input.KeyInterop.KeyFromVirtualKey(lParam.vkCode); //if (HookedKeys.Contains(key)) { KeyboardHookEventArgs kea = new KeyboardHookEventArgs(key, true); if ((wParam == (int)Win32.WindowsMessages.WM_KEYDOWN || wParam == (int)Win32.WindowsMessages.WM_SYSKEYDOWN) && (KeyDown != null)) { KeyDown(this, kea); } else if ((wParam == (int)Win32.WindowsMessages.WM_KEYUP || wParam == (int)Win32.WindowsMessages.WM_SYSKEYUP) && (KeyUp != null)) { kea.IsDown = false; KeyUp(this, kea); } if (kea.Handled) return 1; } } return Win32.CallNextHookEx(m_hHook, code, wParam, ref lParam); }
public static String Get(HTTP.UpdateProgressDelegate progressDelegate, HTTP.FuncBool cancellingDelegate, bool timeout, HTTP.DataCopiedDelegate dataRxDelegate, IXenConnection connection, XenRef <Task> task, ref Session session, string path, string hostname, Delegate f, params object[] p) { log.DebugFormat("HTTP GETTING file from {0} to {1}", hostname, path); // Cannot use ref param in anonymous method, so save it here and restore it later Session _session = session; HTTP.DataCopiedDelegate dataCopiedDelegate = delegate(long bytes) { if (progressDelegate != null) { int progress = (int)(100 * (double)Task.DoWithSessionRetry(connection, ref _session, (Task.TaskProgressOp)Task.get_progress, task.opaque_ref)); progressDelegate(progress); } if (dataRxDelegate != null) { dataRxDelegate(bytes); } }; HTTP.FuncBool cancellingDelegate2 = (HTTP.FuncBool) delegate() { return(XenAdminConfigManager.Provider.ForcedExiting || cancellingDelegate != null && cancellingDelegate()); }; try { List <object> args = new List <object>(); args.Add(dataCopiedDelegate); args.Add(cancellingDelegate2); args.Add(XenAdminConfigManager.Provider.GetProxyTimeout(timeout)); args.Add(hostname); args.Add(XenAdminConfigManager.Provider.GetProxyFromSettings(connection)); args.Add(path); args.Add(task.opaque_ref); // task_id args.AddRange(p); f.DynamicInvoke(args.ToArray()); } catch (Exception e) { log.DebugFormat("Caught exception doing HTTP GET from {0} to {1}", hostname, path); log.Debug(e, e); if (e is WebException && e.InnerException is IOException && Win32.GetHResult(e.InnerException as IOException) == Win32.ERROR_DISK_FULL) { throw e.InnerException; } else if (e is CancelledException || e.InnerException is CancelledException) { throw new XenAdmin.CancelledException(); } else if (e.InnerException.Message == "Received error code HTTP/1.1 403 Forbidden\r\n from the server") { // RBAC Failure List <Role> roles = connection.Session.Roles; roles.Sort(); throw new Exception(String.Format(Messages.RBAC_HTTP_FAILURE, roles[0].FriendlyName), e); } else { throw e.InnerException; } } return(PollTaskForResult(connection, ref session, cancellingDelegate2, task)); }
private void CreateHook() { uint threadId = Win32.GetWindowThreadProcessId(hWnd, IntPtr.Zero); hHook = Win32.SetWindowsHookEx(Win32.HookType.WH_CALLWNDPROC, wndProcDelegate, IntPtr.Zero, threadId); }
/// <summary> /// Creates the render context provider. Must also create the OpenGL extensions. /// </summary> /// <param name="openGLVersion">The desired OpenGL version.</param> /// <param name="gl">The OpenGL context.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="bitDepth">The bit depth.</param> /// <param name="parameter">The parameter</param> /// <returns></returns> public override bool Create(OpenGLVersion openGLVersion, OpenGL gl, int width, int height, int bitDepth, object parameter) { // Call the base. base.Create(openGLVersion, gl, width, height, bitDepth, parameter); // Create a new window class, as basic as possible. wndClass = new Win32.WNDCLASSEX(); wndClass.Init(); wndClass.style = Win32.ClassStyles.HorizontalRedraw | Win32.ClassStyles.VerticalRedraw | Win32.ClassStyles.OwnDC; wndClass.lpfnWndProc = wndProcDelegate; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = IntPtr.Zero; wndClass.hIcon = IntPtr.Zero; wndClass.hCursor = IntPtr.Zero; wndClass.hbrBackground = IntPtr.Zero; wndClass.lpszMenuName = null; wndClass.lpszClassName = "SharpGLRenderWindow"; wndClass.hIconSm = IntPtr.Zero; Win32.RegisterClassEx(ref wndClass); // Create the window. Position and size it. windowHandle = Win32.CreateWindowEx(0, "SharpGLRenderWindow", "", Win32.WindowStyles.WS_CLIPCHILDREN | Win32.WindowStyles.WS_CLIPSIBLINGS | Win32.WindowStyles.WS_POPUP, 0, 0, width, height, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); // Get the window device context. deviceContextHandle = Win32.GetDC(windowHandle); // Setup a pixel format. Win32.PIXELFORMATDESCRIPTOR pfd = new Win32.PIXELFORMATDESCRIPTOR(); pfd.Init(); pfd.nVersion = 1; pfd.dwFlags = Win32.PFD_DRAW_TO_WINDOW | Win32.PFD_SUPPORT_OPENGL | Win32.PFD_DOUBLEBUFFER; pfd.iPixelType = Win32.PFD_TYPE_RGBA; pfd.cColorBits = (byte)bitDepth; pfd.cDepthBits = 16; pfd.cStencilBits = 8; pfd.iLayerType = Win32.PFD_MAIN_PLANE; // Match an appropriate pixel format int iPixelformat; if ((iPixelformat = Win32.ChoosePixelFormat(deviceContextHandle, pfd)) == 0) { return(false); } // Sets the pixel format if (Win32.SetPixelFormat(deviceContextHandle, iPixelformat, pfd) == 0) { return(false); } // Create the render context. renderContextHandle = Win32.wglCreateContext(deviceContextHandle); // Make the context current. MakeCurrent(); // Update the context if required. UpdateContextVersion(gl); // Return success. return(true); }
public static VerifyResult VerifyFile(string fileName, out string signerName) { VerifyResult result = VerifyResult.NoSignature; using (MemoryAlloc strMem = new MemoryAlloc(fileName.Length * 2 + 2)) { WintrustFileInfo fileInfo = new WintrustFileInfo(); strMem.WriteUnicodeString(0, fileName); strMem.WriteInt16(fileName.Length * 2, 0); fileInfo.Size = Marshal.SizeOf(fileInfo); fileInfo.FilePath = strMem; WintrustData trustData = new WintrustData(); trustData.Size = Marshal.SizeOf(typeof(WintrustData)); trustData.UIChoice = 2; // WTD_UI_NONE trustData.UnionChoice = 1; // WTD_CHOICE_FILE trustData.RevocationChecks = WtdRevocationChecks.None; trustData.ProvFlags = WtdProvFlags.Safer; trustData.StateAction = WtdStateAction.Verify; if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { trustData.ProvFlags |= WtdProvFlags.CacheOnlyUrlRetrieval; } using (MemoryAlloc mem = new MemoryAlloc(fileInfo.Size)) { mem.WriteStruct <WintrustFileInfo>(fileInfo); trustData.UnionData = mem; uint winTrustResult = Win32.WinVerifyTrust(IntPtr.Zero, WintrustActionGenericVerifyV2, ref trustData); result = StatusToVerifyResult(winTrustResult); try { if (result != VerifyResult.NoSignature) { signerName = GetSignerNameFromStateData(trustData.StateData); return(result); } } finally { // Close the state data. trustData.StateAction = WtdStateAction.Close; Win32.WinVerifyTrust(IntPtr.Zero, WintrustActionGenericVerifyV2, ref trustData); } } } signerName = null; using (FileHandle sourceFile = FileHandle.CreateWin32(fileName, FileAccess.GenericRead, FileShareMode.Read, FileCreationDispositionWin32.OpenExisting)) { byte[] hash = new byte[256]; int hashLength = 256; if (!Win32.CryptCATAdminCalcHashFromFileHandle(sourceFile, ref hashLength, hash, 0)) { hash = new byte[hashLength]; if (!Win32.CryptCATAdminCalcHashFromFileHandle(sourceFile, ref hashLength, hash, 0)) { return(VerifyResult.NoSignature); } } StringBuilder memberTag = new StringBuilder(hashLength * 2); for (int i = 0; i < hashLength; i++) { memberTag.Append(hash[i].ToString("X2")); } IntPtr catAdmin; if (!Win32.CryptCATAdminAcquireContext(out catAdmin, DriverActionVerify, 0)) { return(VerifyResult.NoSignature); } IntPtr catInfo = Win32.CryptCATAdminEnumCatalogFromHash(catAdmin, hash, hashLength, 0, IntPtr.Zero); if (catInfo == IntPtr.Zero) { Win32.CryptCATAdminReleaseContext(catAdmin, 0); return(VerifyResult.NoSignature); } CatalogInfo ci; if (!Win32.CryptCATCatalogInfoFromContext(catInfo, out ci, 0)) { Win32.CryptCATAdminReleaseCatalogContext(catAdmin, catInfo, 0); Win32.CryptCATAdminReleaseContext(catAdmin, 0); return(VerifyResult.NoSignature); } WintrustCatalogInfo wci = new WintrustCatalogInfo(); wci.Size = Marshal.SizeOf(wci); wci.CatalogFilePath = ci.CatalogFile; wci.MemberFilePath = fileName; wci.MemberTag = memberTag.ToString(); WintrustData trustData = new WintrustData(); trustData.Size = Marshal.SizeOf(typeof(WintrustData)); trustData.UIChoice = 1; trustData.UnionChoice = 2; trustData.RevocationChecks = WtdRevocationChecks.None; trustData.StateAction = WtdStateAction.Verify; if (OSVersion.IsAboveOrEqual(WindowsVersion.Vista)) { trustData.ProvFlags = WtdProvFlags.CacheOnlyUrlRetrieval; } using (MemoryAlloc mem = new MemoryAlloc(wci.Size)) { mem.WriteStruct <WintrustCatalogInfo>(wci); try { trustData.UnionData = mem; uint winTrustResult = Win32.WinVerifyTrust(IntPtr.Zero, DriverActionVerify, ref trustData); result = StatusToVerifyResult(winTrustResult); if (result != VerifyResult.NoSignature) { signerName = GetSignerNameFromStateData(trustData.StateData); } } finally { try { // Close the state data. trustData.StateAction = WtdStateAction.Close; Win32.WinVerifyTrust(IntPtr.Zero, DriverActionVerify, ref trustData); } finally { Win32.CryptCATAdminReleaseCatalogContext(catAdmin, catInfo, 0); Win32.CryptCATAdminReleaseContext(catAdmin, 0); mem.DestroyStruct <WintrustCatalogInfo>(); } } } } return(result); }
/// <summary> /// Execute a HandBrakeCLI process. /// </summary> /// <param name="encodeQueueTask"> /// The encodeQueueTask. /// </param> /// <param name="enableLogging"> /// Enable Logging. When Disabled we onlt parse Standard Ouput for progress info. Standard Error log data is ignored. /// </param> public void Start(QueueTask encodeQueueTask, bool enableLogging) { try { QueueTask queueTask = encodeQueueTask; if (queueTask == null) { throw new ArgumentNullException("QueueTask was null"); } if (IsEncoding) { throw new Exception("HandBrake is already encodeing."); } IsEncoding = true; if (enableLogging) { try { SetupLogging(queueTask); } catch (Exception) { IsEncoding = false; throw; } } if (Init.PreventSleep) { Win32.PreventSleep(); } string handbrakeCLIPath = Path.Combine(Application.StartupPath, "HandBrakeCLI.exe"); ProcessStartInfo cliStart = new ProcessStartInfo(handbrakeCLIPath, queueTask.Query) { RedirectStandardOutput = true, RedirectStandardError = enableLogging ? true : false, UseShellExecute = false, CreateNoWindow = !Init.ShowCliForInGuiEncodeStatus ? true : false }; this.HbProcess = new Process { StartInfo = cliStart }; this.HbProcess.Start(); if (enableLogging) { this.HbProcess.ErrorDataReceived += HbProcErrorDataReceived; this.HbProcess.BeginErrorReadLine(); } this.processId = HbProcess.Id; this.processHandle = HbProcess.Handle; // Set the process Priority if (this.processId != -1) { this.HbProcess.EnableRaisingEvents = true; this.HbProcess.Exited += this.HbProcessExited; } // Set the Process Priority switch (Init.ProcessPriority) { case "Realtime": this.HbProcess.PriorityClass = ProcessPriorityClass.RealTime; break; case "High": this.HbProcess.PriorityClass = ProcessPriorityClass.High; break; case "Above Normal": this.HbProcess.PriorityClass = ProcessPriorityClass.AboveNormal; break; case "Normal": this.HbProcess.PriorityClass = ProcessPriorityClass.Normal; break; case "Low": this.HbProcess.PriorityClass = ProcessPriorityClass.Idle; break; default: this.HbProcess.PriorityClass = ProcessPriorityClass.BelowNormal; break; } // Fire the Encode Started Event if (this.EncodeStarted != null) { this.EncodeStarted(this, new EventArgs()); } } catch (Exception exc) { if (this.EncodeCompleted != null) { this.EncodeCompleted(this, new EncodeCompletedEventArgs(false, exc, "An Error has occured in EncodeService.Run()")); } } }
//ISocketWithTimeoutClient これらはこのウィンドウとは別のスレッドで実行されるので慎重に public void SuccessfullyExit(object result) { _result = (ConnectionTag)result; //_result.SetServerInfo(((TCPTerminalParam)_result.Param).Host, swt.IPAddress); Win32.SendMessage(_savedHWND, GConst.WMG_ASYNCCONNECT, IntPtr.Zero, new IntPtr(1)); }
/// <summary> /// Sends a win32 message to set scrollbars position. /// </summary> /// <param name="point">a POINT conatining H/Vscrollbar scrollpos.</param> private unsafe void SetScrollPos(Win32.POINT point) { IntPtr ptr = new IntPtr(&point); Win32.SendMessage(richTextBox1.Handle, Win32.EM_SETSCROLLPOS, 0, ptr); }
public static bool ExistPlayDevice() { return(Win32.waveOutGetNumDevs() > 0 ? true : false); }
public void PopulateBITMAPINFOHEADER32(ref Win32.BITMAPINFOHEADER bmih) { bmih.Init(); bmih.biPlanes = 1; bmih.biBitCount = 32; bmih.biHeight = height; bmih.biWidth = width; bmih.biSizeImage = (uint)(4 * width * height); }
public static CodecToken TakePossession(Win32.AVICOMPRESSOPTIONS comprOptions) { CodecToken ret = new CodecToken(); ret.allocated = true; ret.comprOptions = comprOptions; ret.codec = Win32.decode_mmioFOURCC(comprOptions.fccHandler); return ret; }
public void Dispose() => Win32.UnhookWinEvent(hookId);
/// <summary> /// With this class you are able to listen to global window event(s). /// </summary> /// <param name="winEvent"><see cref="WINEVENT"/></param> /// <param name="dwFlags"><see cref="WINEVENT.WINEVENT_OUTOFCONTEXT"/> | <see cref="WINEVENT.WINEVENT_SKIPOWNPROCESS"/></param> public WindowEventListener(uint winEvent, uint dwFlags) { win32EventHandler = new Win32.WinEventDelegate(desktop_win32EventRaised); hookId = Win32.SetWinEventHook(winEvent, winEvent, IntPtr.Zero, win32EventHandler, 0, 0, dwFlags); }
public void ConnectionFailed(string message) { _errorMessage = message; Win32.SendMessage(_savedHWND, GConst.WMG_ASYNCCONNECT, IntPtr.Zero, IntPtr.Zero); }
/// <summary> /// When overridden in a derived class, executes the code required to free the handle. /// </summary> /// <returns> /// <see langword="true"/> if the handle is released successfully; otherwise, in the event /// of a catastrophic failure, <see langword="false"/>. In this case, it generates a /// releaseHandleFailed MDA Managed Debugging Assistant. /// </returns> protected override bool ReleaseHandle() { return(Win32.FreeLibrary(handle)); }
protected override void DisposeObject(bool disposing) { Win32.RtlDestroyQueryDebugBuffer(_buffer); }
public static bool ExistRecordDevice() { return(Win32.waveInGetNumDevs() > 0 ? true : false); }
/// <summary> /// This method will use User32 code to capture the specified captureBounds from the screen /// </summary> /// <param name="captureBounds">Rectangle with the bounds to capture</param> /// <returns>Bitmap which is captured from the screen at the location specified by the captureBounds</returns> public static Bitmap CaptureRectangle(Rectangle captureBounds) { Bitmap returnBitmap = null; if (captureBounds.Height <= 0 || captureBounds.Width <= 0) { LOG.Warn("Nothing to capture, ignoring!"); return(null); } else { LOG.Debug("CaptureRectangle Called!"); } // .NET GDI+ Solution, according to some post this has a GDI+ leak... // See http://connect.microsoft.com/VisualStudio/feedback/details/344752/gdi-object-leak-when-calling-graphics-copyfromscreen // Bitmap capturedBitmap = new Bitmap(captureBounds.Width, captureBounds.Height); // using (Graphics graphics = Graphics.FromImage(capturedBitmap)) { // graphics.CopyFromScreen(captureBounds.Location, Point.Empty, captureBounds.Size, CopyPixelOperation.CaptureBlt); // } // capture.Image = capturedBitmap; // capture.Location = captureBounds.Location; using (SafeWindowDCHandle desktopDCHandle = SafeWindowDCHandle.fromDesktop()) { if (desktopDCHandle.IsInvalid) { // Get Exception before the error is lost Exception exceptionToThrow = CreateCaptureException("desktopDCHandle", captureBounds); // throw exception throw exceptionToThrow; } // create a device context we can copy to using (SafeCompatibleDCHandle safeCompatibleDCHandle = GDI32.CreateCompatibleDC(desktopDCHandle)) { // Check if the device context is there, if not throw an error with as much info as possible! if (safeCompatibleDCHandle.IsInvalid) { // Get Exception before the error is lost Exception exceptionToThrow = CreateCaptureException("CreateCompatibleDC", captureBounds); // throw exception throw exceptionToThrow; } // Create BitmapInfoHeader for CreateDIBSection BitmapInfoHeader bmi = new BitmapInfoHeader(captureBounds.Width, captureBounds.Height, 24); // Make sure the last error is set to 0 Win32.SetLastError(0); // create a bitmap we can copy it to, using GetDeviceCaps to get the width/height IntPtr bits0; // not used for our purposes. It returns a pointer to the raw bits that make up the bitmap. using (SafeDibSectionHandle safeDibSectionHandle = GDI32.CreateDIBSection(desktopDCHandle, ref bmi, BitmapInfoHeader.DIB_RGB_COLORS, out bits0, IntPtr.Zero, 0)) { if (safeDibSectionHandle.IsInvalid) { // Get Exception before the error is lost Exception exceptionToThrow = CreateCaptureException("CreateDIBSection", captureBounds); exceptionToThrow.Data.Add("hdcDest", safeCompatibleDCHandle.DangerousGetHandle().ToInt32()); exceptionToThrow.Data.Add("hdcSrc", desktopDCHandle.DangerousGetHandle().ToInt32()); // Throw so people can report the problem throw exceptionToThrow; } else { // select the bitmap object and store the old handle using (SafeSelectObjectHandle selectObject = safeCompatibleDCHandle.SelectObject(safeDibSectionHandle)) { // bitblt over (make copy) GDI32.BitBlt(safeCompatibleDCHandle, 0, 0, captureBounds.Width, captureBounds.Height, desktopDCHandle, captureBounds.X, captureBounds.Y, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt); } // get a .NET image object for it // A suggestion for the "A generic error occurred in GDI+." E_FAIL/0×80004005 error is to re-try... bool success = false; ExternalException exception = null; for (int i = 0; i < 3; i++) { try { // Collect all screens inside this capture List <Screen> screensInsideCapture = new List <Screen>(); foreach (Screen screen in Screen.AllScreens) { if (screen.Bounds.IntersectsWith(captureBounds)) { screensInsideCapture.Add(screen); } } // Check all all screens are of an equal size bool offscreenContent = false; using (Region captureRegion = new Region(captureBounds)) { // Exclude every visible part foreach (Screen screen in screensInsideCapture) { captureRegion.Exclude(screen.Bounds); } // If the region is not empty, we have "offscreenContent" using (Graphics screenGraphics = Graphics.FromHwnd(User32.GetDesktopWindow())) { offscreenContent = !captureRegion.IsEmpty(screenGraphics); } } // Check if we need to have a transparent background, needed for offscreen content if (offscreenContent) { using (Bitmap tmpBitmap = Bitmap.FromHbitmap(safeDibSectionHandle.DangerousGetHandle())) { // Create a new bitmap which has a transparent background returnBitmap = ImageHelper.CreateEmpty(tmpBitmap.Width, tmpBitmap.Height, PixelFormat.Format32bppArgb, Color.Transparent, tmpBitmap.HorizontalResolution, tmpBitmap.VerticalResolution); // Content will be copied here using (Graphics graphics = Graphics.FromImage(returnBitmap)) { // For all screens copy the content to the new bitmap foreach (Screen screen in Screen.AllScreens) { Rectangle screenBounds = screen.Bounds; // Make sure the bounds are offsetted to the capture bounds screenBounds.Offset(-captureBounds.X, -captureBounds.Y); graphics.DrawImage(tmpBitmap, screenBounds, screenBounds.X, screenBounds.Y, screenBounds.Width, screenBounds.Height, GraphicsUnit.Pixel); } } } } else { // All screens, which are inside the capture, are of equal size // assign image to Capture, the image will be disposed there.. returnBitmap = Bitmap.FromHbitmap(safeDibSectionHandle.DangerousGetHandle()); } // We got through the capture without exception success = true; break; } catch (ExternalException ee) { LOG.Warn("Problem getting bitmap at try " + i + " : ", ee); exception = ee; } } if (!success) { LOG.Error("Still couldn't create Bitmap!"); throw exception; } } } } } return(returnBitmap); }
/// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary> /// <returns>A signed integer that indicates the relative values of <paramref name="a" /> and <paramref name="b" />, as shown in the following table.Value Meaning Less than zero<paramref name="a" /> is less than <paramref name="b" />.Zero<paramref name="a" /> equals <paramref name="b" />.Greater than zero<paramref name="a" /> is greater than <paramref name="b" />.</returns> /// <param name="a">The first object to compare.</param> /// <param name="b">The second object to compare.</param> public int Compare(string a, string b) { return(Win32.StrCmpLogicalW(a, b)); }
internal void DrawControl(Graphics g) { if (!Visible) { return; } //Rectangle TabControlArea = new Rectangle(2, 2, this.Width - 3, this.Height - 2); Rectangle TabControlArea = this.ClientRectangle; Rectangle TabArea = new Rectangle(3, 24, this.ClientRectangle.Width - 7, this.ClientRectangle.Height - 28);// this.DisplayRectangle; //---------------------------- // fill client area Brush br = new SolidBrush(Shared.ControlBackColor); g.FillRectangle(br, TabControlArea); br.Dispose(); //---------------------------- //---------------------------- // draw border int nDelta = SystemInformation.Border3DSize.Width; //yuterz //Pen border = new Pen(SystemColors.ControlDark); Pen border = new Pen(Shared.ControlBorderBackColor); //TabArea.Inflate(nDelta, nDelta); g.DrawRectangle(border, TabArea); // g.FillRectangle(new this.TabArea); border.Dispose(); //---------------------------- //---------------------------- // clip region for drawing tabs Region rsaved = g.Clip; Rectangle rreg; int nWidth = TabArea.Width + nMargin; if (bUpDown) { // exclude updown control for painting if (Win32.IsWindowVisible(scUpDown.Handle)) { Rectangle rupdown = new Rectangle(); Win32.GetWindowRect(scUpDown.Handle, ref rupdown); Rectangle rupdown2 = this.RectangleToClient(rupdown); nWidth = rupdown2.X; } } rreg = new Rectangle(TabArea.Left, TabControlArea.Top, nWidth - nMargin, TabControlArea.Height); g.SetClip(rreg); // draw tabs for (int i = 0; i < this.TabCount; i++) { DrawTab(g, this.TabPages[i], i); } g.Clip = rsaved; //---------------------------- //yuterz //---------------------------- // draw background to cover flat border areas if (this.SelectedTab != null) { TabPage tabPage = this.SelectedTab; Color color = tabPage.BackColor; //border = new Pen(color); border = new Pen(Color.Green); TabArea.Offset(1, 1); TabArea.Width -= 2; TabArea.Height -= 2; //g.DrawRectangle(border, TabArea); TabArea.Width -= 1; TabArea.Height -= 1; // g.DrawRectangle(border, TabArea); border.Dispose(); } //---------------------------- }
/// ------------------------------------------------------------------------------------ /// <summary> /// Translate mouse buttons received from a Win API mouse message to .NET mouse buttons /// </summary> /// <param name="winMouseButtons">Windows mouse buttons</param> /// <returns>.NET mouse buttons</returns> /// ------------------------------------------------------------------------------------ public static MouseButtons TranslateMouseButtons(Win32.MouseButtons winMouseButtons) { MouseButtons mouseButton = MouseButtons.None; if ((winMouseButtons & Win32.MouseButtons.MK_LBUTTON) == Win32.MouseButtons.MK_LBUTTON) mouseButton |= MouseButtons.Left; if ((winMouseButtons & Win32.MouseButtons.MK_RBUTTON) == Win32.MouseButtons.MK_RBUTTON) mouseButton |= MouseButtons.Right; if ((winMouseButtons & Win32.MouseButtons.MK_MBUTTON) == Win32.MouseButtons.MK_MBUTTON) mouseButton |= MouseButtons.Middle; if ((winMouseButtons & Win32.MouseButtons.MK_XBUTTON1) == Win32.MouseButtons.MK_XBUTTON1) mouseButton |= MouseButtons.XButton1; if ((winMouseButtons & Win32.MouseButtons.MK_XBUTTON2) == Win32.MouseButtons.MK_XBUTTON2) mouseButton |= MouseButtons.XButton2; return mouseButton; }
public static Color GetPixelColor(this Control c, int x, int y) { var screenCoords = c.PointToScreen(new Point(x, y)); return(Win32.GetPixelColor(screenCoords.X, screenCoords.Y)); }
internal void DrawIcons(Graphics g) { if ((leftRightImages == null) || (leftRightImages.Images.Count != 4)) { return; } //---------------------------- // calc positions Rectangle TabControlArea = this.ClientRectangle; Rectangle r0 = new Rectangle(); Win32.GetClientRect(scUpDown.Handle, ref r0); // Brush br = new SolidBrush(SystemColors.Control); Brush br = new SolidBrush(Shared.ControlBackColor); g.FillRectangle(br, r0); br.Dispose(); Pen border = new Pen(Shared.ControlBorderBackColor); Rectangle rborder = new Rectangle(1, 1, 36, 19); rborder.Inflate(-1, -1); g.DrawRectangle(border, rborder); border.Dispose(); int nMiddle = (r0.Width / 2); int nTop = (r0.Height - 16) / 2; int nLeft = (nMiddle - 16) / 2; Rectangle r1 = new Rectangle(nLeft, nTop, 16, 16); Rectangle r2 = new Rectangle(nMiddle + nLeft, nTop, 16, 16); //---------------------------- //---------------------------- // draw buttons Image img = leftRightImages.Images[1]; if (img != null) { if (this.TabCount > 0) { Rectangle r3 = this.GetTabRect(0); if (r3.Left < TabControlArea.Left) { g.DrawImage(img, r1); } else { img = leftRightImages.Images[3]; if (img != null) { g.DrawImage(img, r1); } } } } img = leftRightImages.Images[0]; if (img != null) { if (this.TabCount > 0) { Rectangle r3 = this.GetTabRect(this.TabCount - 1); if (r3.Right > (TabControlArea.Width - r0.Width)) { g.DrawImage(img, r2); } else { img = leftRightImages.Images[2]; if (img != null) { g.DrawImage(img, r2); } } } } //---------------------------- }
public Font(int height, string fontName) { this._hFont = Win32.CreateFont(height, 0, 0, 0, 0, 0U, 0U, 0U, 0U, 2U, 0U, 0U, 0U, fontName); }
/// <summary> /// Retrieves the names of all loaded modules in the process, their base /// address and size on disk. /// </summary> /// /// <param name="pid"> /// Id of the process. /// </param> private void GetModuleDetails(int pid) { const Win32.SnapshotFlags flags = Win32.SnapshotFlags.TH32CS_SNAPMODULE | Win32.SnapshotFlags.TH32CS_SNAPMODULE32; var hModuleSnap = Win32.CreateToolhelp32Snapshot(flags, pid); if (hModuleSnap == INVALID_HANDLE_VALUE) { return; } var modEntry = new Win32.MODULEENTRY32() { dwSize = (uint)Marshal.SizeOf(typeof(Win32.MODULEENTRY32)), th32ModuleID = 0 }; if (!Win32.Module32First(hModuleSnap, ref modEntry)) { Win32.CloseHandle(hModuleSnap); return; } do { try { var modPath = modEntry.szExePath; var modInfo = FileVersionInfo.GetVersionInfo(modPath); var modSize = new FileInfo(modPath).Length; var lvi = new ListViewItem(modEntry.szModule) { Tag = modInfo.FileName, ToolTipText = modInfo.FileName + "\n" + modInfo.LegalCopyright + "\n" + modInfo.FileDescription + "\n" + modInfo.ProductVersion }; lvi.SubItems.Add("0x" + modEntry.modBaseAddr.ToString("X4")); lvi.SubItems.Add(FormatByteSize(modSize)); LV_Module.Items.Add(lvi); } catch { break; } }while (Win32.Module32Next(hModuleSnap, ref modEntry)); // Close the object Win32.CloseHandle(hModuleSnap); /* Sort the items and remove the duplicate module name. The ** duplication happens because SnapshotFlags searches for both 32-bit ** and 64-bit modules. Therefore, it adds the main module from both ** TH32CS_SNAPMODULE and TH32CS_SNAPMODULE32. */ LV_Module.Items[0].ForeColor = Color.Red; LV_Module.Sorting = SortOrder.Ascending; for (var i = 0; i < LV_Module.Items.Count - 1; i++) { if (LV_Module.Items[i].Tag.Equals(LV_Module.Items[i + 1].Tag)) { LV_Module.Items[i].ForeColor = Color.Red; LV_Module.Items[i + 1].Remove(); i--; } moduleCount = i; } SetModuleCount(); }
public unsafe Bitmap Apply(Bitmap srcImg) { int num5; if (srcImg.PixelFormat != PixelFormat.Format8bppIndexed) { throw new ArgumentException(); } int width = srcImg.Width; int height = srcImg.Height; BitmapData bitmapdata = srcImg.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed); Bitmap bitmap = GodLesZ.Library.Imaging.Image.CreateGrayscaleImage(width, height); BitmapData data2 = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed); int stride = data2.Stride; int num4 = stride - width; Win32.memset(data2.Scan0, this.bg, stride * height); byte *numPtr = (byte *)bitmapdata.Scan0.ToPointer(); byte *numPtr2 = (byte *)data2.Scan0.ToPointer(); byte *numPtr3 = numPtr; byte *numPtr4 = numPtr2; for (int i = 0; i < height; i++) { num5 = -1; int num7 = 0; while (num7 < width) { if (num5 == -1) { if (numPtr3[0] == this.fg) { num5 = num7; } } else if (numPtr3[0] != this.fg) { numPtr4[num5 + ((num7 - num5) >> 1)] = this.fg; num5 = -1; } num7++; numPtr3++; } if (num5 != -1) { numPtr4[num5 + ((width - num5) >> 1)] = this.fg; } numPtr3 += num4; numPtr4 += stride; } for (int j = 0; j < width; j++) { numPtr3 = numPtr + j; numPtr4 = numPtr2 + j; num5 = -1; int num9 = 0; while (num9 < height) { if (num5 == -1) { if (numPtr3[0] == this.fg) { num5 = num9; } } else if (numPtr3[0] != this.fg) { numPtr4[stride * (num5 + ((num9 - num5) >> 1))] = this.fg; num5 = -1; } num9++; numPtr3 += stride; } if (num5 != -1) { numPtr4[stride * (num5 + ((height - num5) >> 1))] = this.fg; } } bitmap.UnlockBits(data2); srcImg.UnlockBits(bitmapdata); return(bitmap); }
private void WmGetMinMaxInfo(IntPtr hwnd, IntPtr lParam) { // MINMAXINFO structure Win32.MINMAXINFO mmi = (Win32.MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(Win32.MINMAXINFO)); // Get handle for nearest monitor to this window WindowInteropHelper wih = new WindowInteropHelper(this); IntPtr hMonitor = Win32.MonitorFromWindow(wih.Handle, Win32.MONITOR_DEFAULTTONEAREST); // Get monitor info Win32.MONITORINFOEX monitorInfo = new Win32.MONITORINFOEX(); monitorInfo.cbSize = Marshal.SizeOf(monitorInfo); Win32.GetMonitorInfo(new HandleRef(this, hMonitor), monitorInfo); // Get HwndSource HwndSource source = HwndSource.FromHwnd(wih.Handle); if (source == null) { // Should never be null throw new Exception("Cannot get HwndSource instance."); } if (source.CompositionTarget == null) { // Should never be null throw new Exception("Cannot get HwndTarget instance."); } // Get transformation matrix //取消了DPI相关转换 //Matrix matrix = source.CompositionTarget.TransformFromDevice; // Convert working area Win32.RECT workingArea = monitorInfo.rcWork; Point dpiIndependentSize = new Point(//注释DPI转换相关 workingArea.Right - workingArea.Left, workingArea.Bottom - workingArea.Top ); //Point dpiIndependentSize = // matrix.Transform(new Point( // workingArea.Right - workingArea.Left, // workingArea.Bottom - workingArea.Top // )); // Convert minimum size Point dpiIndenpendentTrackingSize = new Point(//取消DPI相关转换 this.MinWidth, this.MinHeight ); //Point dpiIndenpendentTrackingSize = matrix.Transform(new Point( // this.MinWidth, // this.MinHeight // )); // Set the maximized size of the window mmi.ptMaxSize.x = (int)dpiIndependentSize.X; mmi.ptMaxSize.y = (int)dpiIndependentSize.Y; // Set the position of the maximized window mmi.ptMaxPosition.x = 0; mmi.ptMaxPosition.y = 0; // Set the minimum tracking size mmi.ptMinTrackSize.x = (int)dpiIndenpendentTrackingSize.X; mmi.ptMinTrackSize.y = (int)dpiIndenpendentTrackingSize.Y; Marshal.StructureToPtr(mmi, lParam, true); }
// Thread entry point public void WorkerThread() { // grabber Grabber grabber = new Grabber(this); // objects object graphObj = null; object sourceObj = null; object grabberObj = null; // interfaces IGraphBuilder graph = null; IBaseFilter sourceBase = null; IBaseFilter grabberBase = null; ISampleGrabber sg = null; IMediaControl mc = null; try { // Get type for filter graph Type srvType = Type.GetTypeFromCLSID(Clsid.FilterGraph); if (srvType == null) { throw new ApplicationException("Failed creating filter graph"); } // create filter graph graphObj = Activator.CreateInstance(srvType); graph = (IGraphBuilder)graphObj; // ---- UCOMIBindCtx bindCtx = null; UCOMIMoniker moniker = null; int n = 0; // create bind context if (Win32.CreateBindCtx(0, out bindCtx) == 0) { // convert moniker`s string to a moniker if (Win32.MkParseDisplayName(bindCtx, source, ref n, out moniker) == 0) { // get device base filter Guid filterId = typeof(IBaseFilter).GUID; moniker.BindToObject(null, null, ref filterId, out sourceObj); Marshal.ReleaseComObject(moniker); moniker = null; } Marshal.ReleaseComObject(bindCtx); bindCtx = null; } // ---- if (sourceObj == null) { throw new ApplicationException("Failed creating device object for moniker"); } sourceBase = (IBaseFilter)sourceObj; // Get type for sample grabber srvType = Type.GetTypeFromCLSID(Clsid.SampleGrabber); if (srvType == null) { throw new ApplicationException("Failed creating sample grabber"); } // create sample grabber grabberObj = Activator.CreateInstance(srvType); sg = (ISampleGrabber)grabberObj; grabberBase = (IBaseFilter)grabberObj; // add source filter to graph graph.AddFilter(sourceBase, "source"); graph.AddFilter(grabberBase, "grabber"); // set media type AMMediaType mt = new AMMediaType(); mt.majorType = MediaType.Video; mt.subType = MediaSubType.RGB24; sg.SetMediaType(mt); // connect pins if (graph.Connect(DSTools.GetOutPin(sourceBase, 0), DSTools.GetInPin(grabberBase, 0)) < 0) { throw new ApplicationException("Failed connecting filters"); } // get media type if (sg.GetConnectedMediaType(mt) == 0) { VideoInfoHeader vih = (VideoInfoHeader)Marshal.PtrToStructure(mt.formatPtr, typeof(VideoInfoHeader)); System.Diagnostics.Debug.WriteLine("width = " + vih.BmiHeader.Width + ", height = " + vih.BmiHeader.Height); grabber.Width = vih.BmiHeader.Width; grabber.Height = vih.BmiHeader.Height; mt.Dispose(); } // render graph.Render(DSTools.GetOutPin(grabberBase, 0)); // sg.SetBufferSamples(false); sg.SetOneShot(false); sg.SetCallback(grabber, 1); // window IVideoWindow win = (IVideoWindow)graphObj; win.put_AutoShow(false); win = null; // get media control mc = (IMediaControl)graphObj; // run mc.Run(); while (!stopEvent.WaitOne(0, true)) { Thread.Sleep(100); } mc.StopWhenReady(); } // catch any exceptions catch (Exception e) { System.Diagnostics.Debug.WriteLine("----: " + e.Message); } // finalization block finally { // release all objects mc = null; graph = null; sourceBase = null; grabberBase = null; sg = null; if (graphObj != null) { Marshal.ReleaseComObject(graphObj); graphObj = null; } if (sourceObj != null) { Marshal.ReleaseComObject(sourceObj); sourceObj = null; } if (grabberObj != null) { Marshal.ReleaseComObject(grabberObj); grabberObj = null; } } }
static private IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) { return(Win32.DefWindowProc(hWnd, msg, wParam, lParam)); }
public Font(string fontName) { this._hFont = Win32.CreateFont(0, 0, 0, 0, 0, 0U, 0U, 0U, 0U, 2U, 0U, 0U, 0U, fontName); }
//发送消息 private void sendmessage(int msg) { Win32 mywin32 = new Win32(); mywin32.SendMsgToMainForm(hwnd.ToInt32(),msg); }
/// <summary> /// Finds the device. /// </summary> /// <param name="classGuid">The class GUID.</param> /// <returns>Device path.</returns> private static string FindDevice(Guid classGuid) { // 0x12 = DIGCF_PRESENT | DIGCF_DEVICEINTERFACE IntPtr handle = Win32.SetupDiGetClassDevs(ref classGuid, 0, IntPtr.Zero, 0x12); int lastError = Marshal.GetLastWin32Error(); if (handle.ToInt32() == -1) { throw new Win32Exception(lastError); } string devicePath = null; for (int deviceIndex = 0; ; deviceIndex++) { Win32.DeviceInfoData deviceInfoData = new Win32.DeviceInfoData(); deviceInfoData.Size = Marshal.SizeOf(deviceInfoData); if (!Win32.SetupDiEnumDeviceInfo(handle, deviceIndex, ref deviceInfoData)) { // out of devices or do we have an error? lastError = Marshal.GetLastWin32Error(); if (lastError != 0x0103 && lastError != 0x007E) { Win32.SetupDiDestroyDeviceInfoList(handle); throw new Win32Exception(lastError); } Win32.SetupDiDestroyDeviceInfoList(handle); break; } Win32.DeviceInterfaceData deviceInterfaceData = new Win32.DeviceInterfaceData(); deviceInterfaceData.Size = Marshal.SizeOf(deviceInterfaceData); if (!Win32.SetupDiEnumDeviceInterfaces(handle, ref deviceInfoData, ref classGuid, 0, ref deviceInterfaceData)) { Win32.SetupDiDestroyDeviceInfoList(handle); throw new Win32Exception(Marshal.GetLastWin32Error()); } uint cbData = 0; if (!Win32.SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, IntPtr.Zero, 0, ref cbData, IntPtr.Zero) && cbData == 0) { Win32.SetupDiDestroyDeviceInfoList(handle); throw new Win32Exception(Marshal.GetLastWin32Error()); } Win32.DeviceInterfaceDetailData deviceInterfaceDetailData = new Win32.DeviceInterfaceDetailData { Size = 5 }; if (!Win32.SetupDiGetDeviceInterfaceDetail(handle, ref deviceInterfaceData, ref deviceInterfaceDetailData, cbData, IntPtr.Zero, IntPtr.Zero)) { Win32.SetupDiDestroyDeviceInfoList(handle); throw new Win32Exception(Marshal.GetLastWin32Error()); } if (deviceInterfaceDetailData.DevicePath.IndexOf(DevicePathVidPid, StringComparison.OrdinalIgnoreCase) != -1) { Win32.SetupDiDestroyDeviceInfoList(handle); devicePath = deviceInterfaceDetailData.DevicePath; break; } } return(devicePath); }
public void PopulateWAVEFORMATEX(ref Win32.WAVEFORMATEX wfex) { int bytes = 0; if (a_bits == 16) bytes = 2; else if (a_bits == 8) bytes = 1; else throw new InvalidOperationException("only 8/16 bits audio are supported by AviWriter and you chose: " + a_bits); if (a_channels == 1) { } else if (a_channels == 2) { } else throw new InvalidOperationException("only 1/2 channels audio are supported by AviWriter and you chose: " + a_channels); wfex.Init(); wfex.nBlockAlign = (ushort)(bytes * a_channels); wfex.nChannels = (ushort)a_channels; wfex.wBitsPerSample = (ushort)a_bits; wfex.wFormatTag = Win32.WAVE_FORMAT_PCM; wfex.nSamplesPerSec = (uint)a_samplerate; wfex.nAvgBytesPerSec = (uint)(wfex.nBlockAlign * a_samplerate); }
/// <summary> /// Returns account name for the SID /// </summary> public static string LookupAccount(string systemName, SecurityIdentifier accountSid) { // parameters validation if (accountSid == null) { throw new ArgumentNullException("accountSid"); } uint cbAccountName = 256; IntPtr pAccountName = IntPtr.Zero; uint cbDomainName = 256; IntPtr pDomainName = IntPtr.Zero; try { while (true) { // allocate buffers pAccountName = Win32.LocalAlloc(Win32.LMEM_FIXED, cbAccountName); pDomainName = Win32.LocalAlloc(Win32.LMEM_FIXED, cbDomainName); if ((pAccountName == IntPtr.Zero) || (pDomainName == IntPtr.Zero)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } // lookup for account int accountType; if (SecurityNative.LookupAccountSid( systemName, accountSid.Handle, pAccountName, ref cbAccountName, pDomainName, ref cbDomainName, out accountType)) { return(Marshal.PtrToStringUni(pDomainName) + "\\" + Marshal.PtrToStringUni(pAccountName)); } else { int error = Marshal.GetLastWin32Error(); if (error != Win32.ERROR_OUTOFMEMORY) { throw new Win32Exception(error); } } } } finally { if (pAccountName != IntPtr.Zero) { Win32.LocalFree(pAccountName); } if (pDomainName != IntPtr.Zero) { Win32.LocalFree(pDomainName); } } }
static int AVISaveOptions(IntPtr stream, ref Win32.AVICOMPRESSOPTIONS opts, IntPtr owner) { IntPtr mem = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32.AVICOMPRESSOPTIONS))); Marshal.StructureToPtr(opts, mem, false); IntPtr[] streams = new[] { stream }; IntPtr[] infPtrs = new[] { mem }; int ret = Win32.AVISaveOptions(owner, 0, 1, streams, infPtrs); opts = (Win32.AVICOMPRESSOPTIONS)Marshal.PtrToStructure(mem, typeof(Win32.AVICOMPRESSOPTIONS)); Marshal.FreeHGlobal(mem); return ret; }
/// <summary> /// We need to do some P/Invoke magic to get the windows on screen /// </summary> /// <param name="unsorted"></param> /// <returns></returns> private IEnumerable <Window> SortWindowsTopToBottom(IEnumerable <Window> unsorted) { var byHandle = unsorted.ToDictionary(win => ((HwndSource)PresentationSource.FromVisual(win)).Handle); for (IntPtr hWnd = Win32.GetTopWindow(IntPtr.Zero); hWnd != IntPtr.Zero; hWnd = Win32.GetWindow(hWnd, Win32.GW_HWNDNEXT)) { if (byHandle.ContainsKey(hWnd)) { yield return(byHandle[hWnd]); } } }
// ------------------------------------------------------------------ #endregion #region Private member. // ------------------------------------------------------------------ /// <summary> /// Called when [custom draw]. /// </summary> /// <param name="idCtrl">The id CTRL.</param> /// <param name="nmcd">The NMCD.</param> /// <returns></returns> private int OnCustomDraw( int idCtrl, ref Win32.NMCUSTOMDRAW nmcd ) { int nResult = 0; switch ( nmcd.dwDrawStage ) { case (int)Win32.CDDS.CDDS_PREPAINT: nResult = interfaceCustDraw.OnPrePaint( idCtrl, ref nmcd ); break; case (int)Win32.CDDS.CDDS_POSTPAINT: nResult = interfaceCustDraw.OnPostPaint( idCtrl, ref nmcd ); break; case (int)Win32.CDDS.CDDS_PREERASE: nResult = interfaceCustDraw.OnPreErase( idCtrl, ref nmcd ); break; case (int)Win32.CDDS.CDDS_POSTERASE: nResult = interfaceCustDraw.OnPostErase( idCtrl, ref nmcd ); break; case (int)Win32.CDDS.CDDS_ITEMPREPAINT: nResult = interfaceCustDraw.OnItemPrePaint( idCtrl, ref nmcd ); break; case (int)Win32.CDDS.CDDS_ITEMPOSTPAINT: nResult = interfaceCustDraw.OnItemPostPaint( idCtrl, ref nmcd ); break; case (int)Win32.CDDS.CDDS_ITEMPREERASE: nResult = interfaceCustDraw.OnItemPreErase( idCtrl, ref nmcd ); break; case (int)Win32.CDDS.CDDS_ITEMPOSTERASE: nResult = interfaceCustDraw.OnItemPostErase( idCtrl, ref nmcd ); break; default: break; } return nResult; }
private void restoreConfigurationToolStripMenuItem_Click(object sender, EventArgs e) { Show(); WindowState = m_ePrevWindowState; Win32.ShowTopmost(Handle); }
private static bool ConsoleCtrlHandler(Win32.CtrlType ctrlType) { const bool ignore = true; return ignore; }
private int Call(SciMsg msg, int wParam, int lParam) { return((int)Win32.SendMessage(_activeScintilla, msg, wParam, lParam)); }