static WinGLContext() { // Dynamically load the OpenGL32.dll in order to use the extension loading capabilities of Wgl. if (opengl32Handle == IntPtr.Zero) { opengl32Handle = Functions.LoadLibrary(opengl32Name); if (opengl32Handle == IntPtr.Zero) throw new ApplicationException(String.Format("LoadLibrary(\"{0}\") call failed with code {1}", opengl32Name, Marshal.GetLastWin32Error())); Debug.WriteLine(String.Format("Loaded opengl32.dll: {0}", opengl32Handle)); } // We need to create a temp context in order to load // wgl extensions (e.g. for multisampling or GL3). // We cannot rely on OpenTK.Platform.Wgl until we // create the context and call Wgl.LoadAll(). Debug.Print("Creating temporary context for wgl extensions."); using (INativeWindow native = new NativeWindow()) { // Create temporary context and load WGL entry points WinWindowInfo window = native.WindowInfo as WinWindowInfo; ContextHandle temp_context = new ContextHandle(Wgl.Imports.CreateContext(window.DeviceContext)); Wgl.Imports.MakeCurrent(window.DeviceContext, temp_context.Handle); Wgl.LoadAll(); // Query graphics modes ModeSelector = new WinGraphicsMode(temp_context, window.DeviceContext); // Destroy temporary context Wgl.Imports.MakeCurrent(IntPtr.Zero, IntPtr.Zero); Wgl.Imports.DeleteContext(temp_context.Handle); wgl_loaded = true; } }
static void Main () { InstructionsForm instructionsForm = new InstructionsForm (); instructionsForm.Show (); NativeWindow nw = new NativeWindow (); CreateParams cp = new CreateParams (); cp.Caption = "bug #80817"; cp.X = 100; cp.Y = 100; cp.Width = 400; cp.Height = 600; cp.ClassStyle = (int) (ClassStyle.CS_VREDRAW | ClassStyle.CS_HREDRAW); cp.Style = (int) WindowStyles.WS_OVERLAPPEDWINDOW; // create the window. nw.CreateHandle (cp); ShowWindow (nw.Handle, WindowPlacementFlags.SW_SHOWNORMAL); UpdateWindow (nw.Handle); MSG msg = new MSG (); while (GetMessage (ref msg, 0, 0, 0) > 0) { TranslateMessage (ref msg); DispatchMessage (ref msg); } }
INativeWindow ConstructMessageWindow() { Debug.WriteLine("Initializing input driver."); Debug.Indent(); // Create a new message-only window to retrieve WM_INPUT messages. INativeWindow native = new NativeWindow(); native.ProcessEvents(); WinWindowInfo parent = native.WindowInfo as WinWindowInfo; Functions.SetParent(parent.Handle, Constants.MESSAGE_ONLY); native.ProcessEvents(); Debug.Unindent(); return native; }
public IGL_TK(int major_version, int minor_version, bool forward_compatible) { //make an 'offscreen context' so we can at least do things without having to create a window OffscreenNativeWindow = new NativeWindow(); OffscreenNativeWindow.ClientSize = new sd.Size(8, 8); this.GraphicsContext = new GraphicsContext(GraphicsMode.Default, OffscreenNativeWindow.WindowInfo, major_version, minor_version, forward_compatible ? GraphicsContextFlags.ForwardCompatible : GraphicsContextFlags.Default); MakeDefaultCurrent(); //this is important for reasons unknown this.GraphicsContext.LoadAll(); //misc initialization CreateRenderStates(); PurgeStateCache(); }
public WinGraphicsMode() { lock (SyncRoot) { using (INativeWindow native = new NativeWindow()) { modes.AddRange(GetModesARB(native)); if (modes.Count == 0) modes.AddRange(GetModesPFD(native)); if (modes.Count == 0) throw new GraphicsModeException( "No GraphicsMode available. This should never happen, please report a bug at http://www.opentk.com"); } modes.Sort(new GraphicsModeComparer()); } }
public WinGLContext(GraphicsMode format, WinWindowInfo window, IGraphicsContext sharedContext, int major, int minor, GraphicsContextFlags flags) { // There are many ways this code can break when accessed by multiple threads. The biggest offender is // the sharedContext stuff, which will only become valid *after* this constructor returns. // The easiest solution is to serialize all context construction - hence the big lock, below. lock (LoadLock) { if (window == null) throw new ArgumentNullException("window", "Must point to a valid window."); if (window.Handle == IntPtr.Zero) throw new ArgumentException("window", "Must be a valid window."); IntPtr current_context = Wgl.GetCurrentContext(); INativeWindow temp_window = null; TemporaryContext temp_context = null; try { if (current_context == IntPtr.Zero) { // Create temporary context to load WGL extensions temp_window = new NativeWindow(); temp_context = new TemporaryContext(temp_window); current_context = Wgl.GetCurrentContext(); if (current_context != IntPtr.Zero && current_context == temp_context.Context.Handle) { new Wgl().LoadEntryPoints(); } } Debug.Print("OpenGL will be bound to window:{0} on thread:{1}", window.Handle, System.Threading.Thread.CurrentThread.ManagedThreadId); ModeSelector = new WinGraphicsMode(window.DeviceContext); Mode = SetGraphicsModePFD(ModeSelector, format, (WinWindowInfo)window); if (Wgl.SupportsFunction("wglCreateContextAttribsARB")) { try { Debug.Write("Using WGL_ARB_create_context... "); List<int> attributes = new List<int>(); attributes.Add((int)ArbCreateContext.MajorVersion); attributes.Add(major); attributes.Add((int)ArbCreateContext.MinorVersion); attributes.Add(minor); if (flags != 0) { attributes.Add((int)ArbCreateContext.ContextFlags); attributes.Add((int)GetARBContextFlags(flags)); attributes.Add((int)ArbCreateContext.ProfileMask); attributes.Add((int)GetARBContextProfile(flags)); } // According to the docs, " <attribList> specifies a list of attributes for the context. // The list consists of a sequence of <name,value> pairs terminated by the // value 0. [...]" // Is this a single 0, or a <0, 0> pair? (Defensive coding: add two zeroes just in case). attributes.Add(0); attributes.Add(0); Handle = new ContextHandle( Wgl.Arb.CreateContextAttribs( window.DeviceContext, sharedContext != null ? (sharedContext as IGraphicsContextInternal).Context.Handle : IntPtr.Zero, attributes.ToArray())); if (Handle == ContextHandle.Zero) Debug.Print("failed. (Error: {0})", Marshal.GetLastWin32Error()); } catch (Exception e) { Debug.Print(e.ToString()); } } if (Handle == ContextHandle.Zero) { // Failed to create GL3-level context, fall back to GL2. Debug.Write("Falling back to GL2... "); Handle = new ContextHandle(Wgl.CreateContext(window.DeviceContext)); if (Handle == ContextHandle.Zero) Handle = new ContextHandle(Wgl.CreateContext(window.DeviceContext)); if (Handle == ContextHandle.Zero) throw new GraphicsContextException( String.Format("Context creation failed. Wgl.CreateContext() error: {0}.", Marshal.GetLastWin32Error())); } Debug.WriteLine(String.Format("success! (id: {0})", Handle)); } finally { if (temp_context != null) { temp_context.Dispose(); temp_context = null; } if (temp_window != null) { temp_window.Dispose(); temp_window = null; } } } // Todo: is this comment still true? // On intel drivers, wgl entry points appear to change // when creating multiple contexts. As a workaround, // we reload Wgl entry points every time we create a // new context - this solves the issue without any apparent // side-effects (i.e. the old contexts can still be handled // using the new entry points.) // Sigh... MakeCurrent(window); new Wgl().LoadEntryPoints(); if (sharedContext != null) { Marshal.GetLastWin32Error(); Debug.Write(String.Format("Sharing state with context {0}: ", sharedContext)); bool result = Wgl.ShareLists((sharedContext as IGraphicsContextInternal).Context.Handle, Handle.Handle); Debug.WriteLine(result ? "success!" : "failed with win32 error " + Marshal.GetLastWin32Error()); } }
public MainPlugin() { SkeletonForm f = null; CreateBonePointInfo createBonePointInfo = null; Tuple <int, int>[] anchorSelect = null; this.Initialize += (sender, e) => { f = new SkeletonForm(); f.ModeChanged += (sender2, e2) => { createBonePointInfo = null; Plugin.RefreshView(); }; f.CreateAnchor += (sender2, e2) => this.BeginCallback(_ => { bone = _.Objects.FirstOrDefault(o => o.Name.StartsWith("bone")); CreateAnchor(_, f.AnchorMargin, f.SnapAnchorToParent, f.CreateSymmetricalAnchor); }); f.FormClosing += (sender2, e2) => { e2.Cancel = true; f.Hide(); }; f.VisibleChanged += (sender2, e2) => { if (!f.Visible) { this.WindowClose(); } }; }; this.Exit += (sender, e) => f.Dispose(); this.Activate += (sender, e) => { if (e.Value) { EnsureBoneObject(e.Document); if (bone == null) { bone = new Metasequoia.Object { Name = "bone", Color = new Color(1, 0.8f, 0.5f), ColorValid = true, }; this.BeginCallback(_ => _.AddObject(bone)); } f.OnMaterialChanged(e.Document); f.OnObjectChanged(e.Document); f.Show(NativeWindow.FromHandle(Plugin.MainWindowHandle)); } else { createBonePointInfo = null; f.Hide(); } Plugin.RefreshView(); e.Handled = e.Value; }; this.IsActivated += (sender, e) => e.Handled = f.Visible; this.MaterialList += (sender, e) => { if (f.Visible) { f.OnMaterialChanged(e.Document); this.BeginCallback(_ => this.RedrawAllScene()); } }; this.ObjectList += (sender, e) => { if (f.Visible) { f.OnObjectChanged(e.Document); } }; this.Undo += (sender, e) => { if (createBonePointInfo != null) { createBonePointInfo = null; e.Handled = true; } }; this.RightButtonDown += (sender, e) => { if (createBonePointInfo != null) { createBonePointInfo = null; this.RedrawAllScene(); } }; this.LeftButtonDown += (sender, e) => { if (f.Visible) { switch (f.Mode) { case SkeletonMode.Bone: { var scr = new Point(e.X, e.Y, e.Scene.Convert3dToScreen(createBonePointInfo == null ? Point.Zero : createBonePointInfo.BeginWorld).Z); var hit = this.HitTest(e.Scene, new[] { e.X, e.Y }, HitType.Vertex); var pos = hit.HitType == HitType.Vertex ? hit.HitPos : this.GetSnappedPos(e.Scene, e.Scene.ConvertScreenTo3d(ref scr), this.GetEditOption().SnapGrid); if (createBonePointInfo == null) { createBonePointInfo = new CreateBonePointInfo { BeginWorld = pos, BeginVertexIndex = hit.HitType == HitType.Vertex && hit.ObjectIndex == bone.Index ? hit.VertexIndex : -1, } } ; else { createBonePointInfo.EndWorld = pos; createBonePointInfo.EndScreen = scr; createBonePointInfo.HasEnd = true; SetBoneSize(e.Scene, createBonePointInfo, new Point(e.X, e.Y, scr.Z), f.CreateRelativeBone); } this.RedrawAllScene(); e.Handled = true; } break; case SkeletonMode.Anchor: anchorSelect = new[] { Tuple.Create(e.X, e.Y), Tuple.Create(e.X, e.Y), }; e.Handled = true; break; } } }; this.LeftButtonMove += (sender, e) => { if (f.Visible) { switch (f.Mode) { case SkeletonMode.Bone: if (f.CreateNormalBone && createBonePointInfo != null && createBonePointInfo.HasEnd) { SetBoneSize(e.Scene, createBonePointInfo, new Point(e.X, e.Y, 0), f.CreateRelativeBone); this.RedrawAllScene(); e.Handled = true; } break; case SkeletonMode.Anchor: if (anchorSelect != null) { anchorSelect[1] = Tuple.Create(e.X, e.Y); this.RedrawScene(e.Scene); e.Handled = true; } break; } } }; this.LeftButtonUp += (sender, e) => { if (f.Visible) { switch (f.Mode) { case SkeletonMode.Bone: if (createBonePointInfo != null && createBonePointInfo.HasEnd) { this.BeginCallback(document => { if (createBonePointInfo.HasSize || f.CreateRelativeBone) { EnsureBoneObject(document); if (bone != null) { createBonePointInfo = new CreateBonePointInfo { BeginVertexIndex = CreateBone ( document, bone, createBonePointInfo, f.CreateNewMaterial, f.BoneName ), BeginWorld = createBonePointInfo.EndWorld, }; f.OnBoneCreated(); this.UpdateUndo(); } else { createBonePointInfo = null; } } else { createBonePointInfo.HasEnd = false; } this.RedrawAllScene(); e.Handled = true; }); } break; case SkeletonMode.Anchor: if (anchorSelect != null) { var isDrag = Math.Abs(anchorSelect[1].Item1 - anchorSelect[0].Item1) > 4 || Math.Abs(anchorSelect[1].Item2 - anchorSelect[0].Item2) > 4; var isAdd = Control.ModifierKeys.HasFlag(Keys.Shift); var isRemove = Control.ModifierKeys.HasFlag(Keys.Control); if (!isAdd & !isRemove) { e.Document.ClearSelect(Doc.ClearselectAll); } if (isDrag) { var objIdx = e.Document.CurrentObjectIndex; var obj = e.Document.Objects[objIdx]; var beginX = Math.Min(anchorSelect[0].Item1, anchorSelect[1].Item1); var beginY = Math.Min(anchorSelect[0].Item2, anchorSelect[1].Item2); var endX = Math.Max(anchorSelect[0].Item1, anchorSelect[1].Item1); var endY = Math.Max(anchorSelect[0].Item2, anchorSelect[1].Item2); foreach (var i in obj.Vertices) { var scr = e.Scene.Convert3dToScreen(i.Point); if (scr.X >= beginX && scr.X <= endX && scr.Y >= beginY && scr.Y <= endY) { i.IsSelected = !isRemove; } } } else { var test = this.HitTest(e.Scene, new[] { anchorSelect[0].Item1, anchorSelect[0].Item2 }, HitType.Vertex | HitType.Face); if (test.HitType != HitType.None && test.ObjectIndex == e.Document.CurrentObjectIndex) { switch (test.HitType) { case HitType.Vertex: if (isRemove) { e.Document.DeleteSelectVertex(test.ObjectIndex, test.VertexIndex); } else { e.Document.AddSelectVertex(test.ObjectIndex, test.VertexIndex); } break; case HitType.Face: foreach (var i in e.Document.Objects[test.ObjectIndex].Faces[test.FaceIndex].Points) { if (isRemove) { e.Document.DeleteSelectVertex(test.ObjectIndex, i); } else { e.Document.AddSelectVertex(test.ObjectIndex, i); } } break; } } } anchorSelect = null; this.RedrawAllScene(); e.Handled = true; } break; } } }; this.Draw += (sender, e) => { if (!f.Visible) { return; } switch (f.Mode) { case SkeletonMode.Bone: EnsureBoneObject(e.Document); if (bone != null) { using (var c = this.CreateDrawingObject(e.Document, DrawObjectVisibility.Point | DrawObjectVisibility.Line)) { c.Color = highlightColor; c.ColorValid = true; foreach (var i in bone.Faces) { c.AddFace(i.Points.Select(_ => bone.Vertices[_].Point) .Select(c.AddVertex)); } } } if (createBonePointInfo != null) { using (var c = this.CreateDrawingObject(e.Document, DrawObjectVisibility.Point | DrawObjectVisibility.Line)) { var vertices = new Point?[] { createBonePointInfo.BeginWorld, createBonePointInfo.HasEnd ? createBonePointInfo.EndWorld : (Point?)null, createBonePointInfo.HasSize ? createBonePointInfo.SizeWorld : (Point?)null, }.Where(_ => _.HasValue).Select(_ => c.AddVertex(_.Value)); c.Color = workingColor; c.ColorValid = true; c.AddFace(createBonePointInfo.Flip ? vertices.Reverse() : vertices); } } break; case SkeletonMode.Anchor: EnsureBoneObject(e.Document); if (bone != null) { using (var c = this.CreateDrawingObject(e.Document, DrawObjectVisibility.Point | DrawObjectVisibility.Line)) { c.Color = highlightColor; c.ColorValid = true; foreach (var i in bone.Faces.Where(_ => _.Material == e.Document.CurrentMaterialIndex && _.PointCount == 3)) { c.AddFace(i.Points.Select(_ => bone.Vertices[_].Point) .Select(c.AddVertex)); } } } if (anchorSelect != null) { using (var c = this.CreateDrawingObject(e.Document, DrawObjectVisibility.Line)) { var begin = anchorSelect[0]; var end = anchorSelect[1]; var z = e.Scene.Convert3dToScreen(Point.Zero).Z; var vertices = new[] { new Point(begin.Item1, begin.Item2, z), new Point(end.Item1, begin.Item2, z), new Point(end.Item1, end.Item2, z), new Point(begin.Item1, end.Item2, z), } .Select(_ => e.Scene.ConvertScreenTo3d(ref _)) .Select(_ => c.AddVertex(_)) .ToArray(); c.Color = workingColor; c.ColorValid = true; c.AddFace(new[] { vertices[0], vertices[1], }); c.AddFace(new[] { vertices[1], vertices[2], }); c.AddFace(new[] { vertices[2], vertices[3], }); c.AddFace(new[] { vertices[3], vertices[0], }); } } break; } }; }
private NotifyIconWindowListener(NotifyIconHolder container, NativeWindow window) { this._container = container; this.AssignHandle(window.Handle); }
/// <summary> /// Constructs a new instance of a CopyData channel. Called /// automatically by the CopyDataChannels collection. /// </summary> /// <param name="owner">The owning native window</param> /// <param name="channelName">The name of the channel to /// send messages on</param> internal CopyDataChannel(NativeWindow owner, string channelName) { _owner = owner; ChannelName = channelName; AddChannel(); }
/// <summary> /// Constructs a new instance of the CopyDataChannels collection. /// Automatically managed by the CopyData class. /// </summary> /// <param name="owner">The NativeWindow this collection /// will be associated with</param> internal CopyDataChannels(NativeWindow owner) { this.owner = owner; }
GraphicsMode SelectGraphicsModeARB(ColorDepth color, int depth, int stencil, int samples, ColorDepth accum, int buffers, bool stereo) { using (INativeWindow native_window = new NativeWindow()) using (IGraphicsContext context = new GraphicsContext(new GraphicsMode(new ColorFormat(), 0, 0, 0, new ColorFormat(), 2, false), native_window.WindowInfo, 1, 0, GraphicsContextFlags.Default)) { WinWindowInfo window = (WinWindowInfo)native_window.WindowInfo; Debug.Write("Selecting pixel format (ARB)... "); if (Wgl.Delegates.wglChoosePixelFormatARB == null || Wgl.Delegates.wglGetPixelFormatAttribivARB == null) { Debug.WriteLine("failed"); return(null); } int[] attribs = new int[] { (int)WGL_ARB_pixel_format.AccelerationArb, (int)WGL_ARB_pixel_format.AlphaBitsArb, (int)WGL_ARB_pixel_format.RedBitsArb, (int)WGL_ARB_pixel_format.GreenBitsArb, (int)WGL_ARB_pixel_format.BlueBitsArb, (int)WGL_ARB_pixel_format.ColorBitsArb, (int)WGL_ARB_pixel_format.DepthBitsArb, (int)WGL_ARB_pixel_format.StencilBitsArb, (int)WGL_ARB_multisample.SampleBuffersArb, (int)WGL_ARB_multisample.SamplesArb, (int)WGL_ARB_pixel_format.AccumAlphaBitsArb, (int)WGL_ARB_pixel_format.AccumRedBitsArb, (int)WGL_ARB_pixel_format.AccumGreenBitsArb, (int)WGL_ARB_pixel_format.AccumBlueBitsArb, (int)WGL_ARB_pixel_format.AccumBitsArb, (int)WGL_ARB_pixel_format.DoubleBufferArb, (int)WGL_ARB_pixel_format.StereoArb, 0 }; int[] values = new int[attribs.Length]; int[] attribs_values = new int[] { (int)WGL_ARB_pixel_format.AccelerationArb, (int)WGL_ARB_pixel_format.FullAccelerationArb, (int)WGL_ARB_pixel_format.RedBitsArb, color.Red, (int)WGL_ARB_pixel_format.GreenBitsArb, color.Green, (int)WGL_ARB_pixel_format.BlueBitsArb, color.Blue, (int)WGL_ARB_pixel_format.AlphaBitsArb, color.Alpha, (int)WGL_ARB_pixel_format.ColorBitsArb, color.BitsPerPixel, (int)WGL_ARB_pixel_format.DepthBitsArb, depth, (int)WGL_ARB_pixel_format.StencilBitsArb, stencil, (int)WGL_ARB_multisample.SampleBuffersArb, samples > 0 ? 1 : 0, (int)WGL_ARB_multisample.SamplesArb, samples, (int)WGL_ARB_pixel_format.AccumRedBitsArb, accum.Red, (int)WGL_ARB_pixel_format.AccumGreenBitsArb, accum.Green, (int)WGL_ARB_pixel_format.AccumBlueBitsArb, accum.Blue, (int)WGL_ARB_pixel_format.AccumAlphaBitsArb, accum.Alpha, (int)WGL_ARB_pixel_format.AccumBitsArb, accum.BitsPerPixel, (int)WGL_ARB_pixel_format.DoubleBufferArb, 1, (int)WGL_ARB_pixel_format.StereoArb, stereo ? 1 : 0, 0, 0 }; int[] pixel = new int[1], num_formats = new int[1]; Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, null, 1, pixel, num_formats); if (num_formats[0] == 0 || pixel[0] == 0) { // Try again without an accumulator. Many modern cards cannot accelerate multisampled formats with accumulator buffers. attribs_values[10 * 2 + 1] = attribs_values[11 * 2 + 1] = attribs_values[12 * 2 + 1] = attribs_values[13 * 2 + 1] = attribs_values[14 * 2 + 1] = 0; Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, null, 1, pixel, num_formats); } if (num_formats[0] == 0 || pixel[0] == 0) { Debug.WriteLine("failed"); return(null); } // Find out what we really got as a format: Wgl.Arb.GetPixelFormatAttrib(window.DeviceContext, pixel[0], 0, attribs.Length, attribs, values); GraphicsMode mode = new GraphicsMode(new IntPtr(pixel[0]), new ColorDepth(values[1], values[2], values[3], values[4]), values[6], values[7], values[8] != 0 ? values[9] : 0, new ColorDepth(values[10], values[11], values[12], values[13]), values[15] == 1 ? 2 : 1, values[16] == 1 ? true : false); Debug.WriteLine("success!"); return(mode); } }
public InternalWindow(NativeWindow parent, int w, int h, GraphicsMode mode, string title, GameWindowFlags flags) : base(w, h, mode, title, flags) { this.parent = parent; }
public static WindowStyles GetStyles(this NativeWindow window) { return((WindowStyles)UnsafeNativeMethods.GetWindowLong(window.Handle, (int)WindowLongFlags.Style)); }
public bool ProcessEvent(IntPtr callref, IntPtr eventref, IntPtr handle, uint kind, ref MSG msg) { QDPoint qdpoint = new QDPoint(); CGPoint Point = new CGPoint(); Rect window_bounds = new Rect(); IntPtr view_handle = IntPtr.Zero; IntPtr window_handle = IntPtr.Zero; bool client = true; ushort button = 0; Hwnd hwnd; GetEventParameter(eventref, kEventParamMouseLocation, typeQDPoint, IntPtr.Zero, (uint)Marshal.SizeOf(typeof(QDPoint)), IntPtr.Zero, ref qdpoint); GetEventParameter(eventref, kEventParamMouseButton, typeMouseButton, IntPtr.Zero, (uint)Marshal.SizeOf(typeof(ushort)), IntPtr.Zero, ref button); if (button == 1 && ((Driver.ModifierKeys & Keys.Control) != 0)) { button = 2; } Point.x = qdpoint.x; Point.y = qdpoint.y; if (FindWindow(qdpoint, ref window_handle) == 5) { return(true); } GetWindowBounds(handle, 33, ref window_bounds); HIViewFindByID(HIViewGetRoot(handle), new HIViewID(EventHandler.kEventClassWindow, 1), ref window_handle); Point.x -= window_bounds.left; Point.y -= window_bounds.top; HIViewGetSubviewHit(window_handle, ref Point, true, ref view_handle); HIViewConvertPoint(ref Point, window_handle, view_handle); hwnd = Hwnd.ObjectFromHandle(view_handle); if (hwnd != null) { client = (hwnd.ClientWindow == view_handle ? true : false); } if (XplatUICarbon.Grab.Hwnd != IntPtr.Zero) { hwnd = Hwnd.ObjectFromHandle(XplatUICarbon.Grab.Hwnd); client = true; } if (hwnd == null) { return(true); } if (client) { qdpoint.x = (short)Point.x; qdpoint.y = (short)Point.y; Driver.ScreenToClient(hwnd.Handle, ref qdpoint); } else { Point.x = qdpoint.x; Point.y = qdpoint.y; } msg.hwnd = hwnd.Handle; msg.lParam = (IntPtr)((ushort)Point.y << 16 | (ushort)Point.x); switch (kind) { case kEventMouseDown: UpdateMouseState(button, true); msg.message = (client ? Msg.WM_MOUSEMOVE : Msg.WM_NCMOUSEMOVE) + ((button - 1) * 3) + 1; msg.wParam = Driver.GetMousewParam(0); if (ClickPending.Pending && (((DateTime.Now.Ticks - ClickPending.Time) < DoubleClickInterval) && (msg.hwnd == ClickPending.Hwnd) && (msg.wParam == ClickPending.wParam) && (msg.lParam == ClickPending.lParam) && (msg.message == ClickPending.Message))) { msg.message = (client ? Msg.WM_MOUSEMOVE : Msg.WM_NCMOUSEMOVE) + ((button - 1) * 3) + 3; ClickPending.Pending = false; } else { ClickPending.Pending = true; ClickPending.Hwnd = msg.hwnd; ClickPending.Message = msg.message; ClickPending.wParam = msg.wParam; ClickPending.lParam = msg.lParam; ClickPending.Time = DateTime.Now.Ticks; } break; case kEventMouseUp: UpdateMouseState(button, false); msg.message = (client ? Msg.WM_MOUSEMOVE : Msg.WM_NCMOUSEMOVE) + ((button - 1) * 3) + 2; msg.wParam = Driver.GetMousewParam(0); break; case kEventMouseDragged: case kEventMouseMoved: if (XplatUICarbon.Grab.Hwnd == IntPtr.Zero) { IntPtr ht = IntPtr.Zero; if (client) { ht = (IntPtr)HitTest.HTCLIENT; NativeWindow.WndProc((Int32)msg.hwnd, Msg.WM_SETCURSOR, (Int32)msg.hwnd, (Int32)HitTest.HTCLIENT); } else { ht = (IntPtr)NativeWindow.WndProc((Int32)hwnd.client_window, Msg.WM_NCHITTEST, 0, (Int32)msg.lParam); NativeWindow.WndProc((Int32)hwnd.client_window, Msg.WM_SETCURSOR, (Int32)msg.hwnd, (Int32)ht); } } msg.message = (client ? Msg.WM_MOUSEMOVE : Msg.WM_NCMOUSEMOVE); msg.wParam = Driver.GetMousewParam(0); break; case kEventMouseWheelMoved: case kEventMouseScroll: UInt16 axis = 0; Int32 delta = 0; GetEventParameter(eventref, kEventParamMouseWheelAxis, typeMouseWheelAxis, IntPtr.Zero, (uint)Marshal.SizeOf(typeof(UInt16)), IntPtr.Zero, ref axis); GetEventParameter(eventref, kEventParamMouseWheelDelta, typeLongInteger, IntPtr.Zero, (uint)Marshal.SizeOf(typeof(Int32)), IntPtr.Zero, ref delta); if (axis == kEventMouseWheelAxisY) { msg.hwnd = XplatUICarbon.FocusWindow; msg.message = Msg.WM_MOUSEWHEEL; msg.wParam = Driver.GetMousewParam(delta * 40); return(true); } break; default: return(false); } Driver.mouse_position.X = (int)Point.x; Driver.mouse_position.Y = (int)Point.y; return(true); }
public static bool SetWindowText(this NativeWindow window, string text) { return(UnsafeNativeMethods.SetWindowText(window.Handle, text)); }
public static void Close(this NativeWindow window) { window.SendMessage(WindowMessage.Close, 0, 0); }
public static bool PostMessage(this NativeWindow window, WindowMessage msg, uint wparam, uint lparam) { return(UnsafeNativeMethods.PostMessage(window.Handle, msg, wparam, lparam)); }
public static void SetPlacement(this NativeWindow window, WINDOWPLACEMENT placement) { UnsafeNativeMethods.SetWindowPlacement(window.Handle, ref placement); }
private static bool handleSpecialArguments(string[] args, out int retval) { List <string> aa = new List <string>(); int argc = args.Length; for (int i = 0; i < argc; ++i) { if ((args[i] == "?#REG") || (args[i] == "?#UNREG")) { bool doReg = (args[i] == "?#REG"); try { if (i + 2 >= argc) { throw new Exception("syntax error. Too few arguments"); } string appPath = args[i + 1]; IWin32Window wnd = NativeWindow.FromHandle((IntPtr)ulong.Parse(args[i + 2])); if (doReg) { Util.FileTypeRegistration.Register(wnd, appPath); } else { Util.FileTypeRegistration.Unregister(wnd, appPath); } retval = 0; return(false); } catch (Exception ex) { MessageBox.Show("Failed to " + (doReg ? "" : "un") + "register file type: " + ex.ToString()); retval = int.MinValue; return(false); } } else if (args[i] == "?#FILEREG") { try { MemoryStream mem = new MemoryStream(Convert.FromBase64String(args[i + 1])); string ext, desc, iconPath, openCmd; byte[] lenData = new byte[4]; mem.Read(lenData, 0, 4); int len = BitConverter.ToInt32(lenData, 0); byte[] strData = new byte[len]; mem.Read(strData, 0, len); ext = System.Text.Encoding.UTF8.GetString(strData); mem.Read(lenData, 0, 4); len = BitConverter.ToInt32(lenData, 0); strData = new byte[len]; mem.Read(strData, 0, len); desc = System.Text.Encoding.UTF8.GetString(strData); mem.Read(lenData, 0, 4); len = BitConverter.ToInt32(lenData, 0); strData = new byte[len]; mem.Read(strData, 0, len); iconPath = System.Text.Encoding.UTF8.GetString(strData); mem.Read(lenData, 0, 4); len = BitConverter.ToInt32(lenData, 0); strData = new byte[len]; mem.Read(strData, 0, len); openCmd = System.Text.Encoding.UTF8.GetString(strData); IWin32Window wnd = NativeWindow.FromHandle((IntPtr)ulong.Parse(args[i + 2])); Util.FileTypeRegistration.RegisterDataFileType(wnd, ext, desc, iconPath, openCmd); retval = 0; return(false); } catch (Exception ex) { MessageBox.Show("Failed to register file type: " + ex.ToString()); retval = int.MinValue; return(false); } } else if (args[i] == "?#FILEUNREG") { try { string ext = args[i + 1]; IWin32Window wnd = NativeWindow.FromHandle((IntPtr)ulong.Parse(args[i + 2])); Util.FileTypeRegistration.UnregisterDataFileType(wnd, ext); retval = 0; return(false); } catch (Exception ex) { MessageBox.Show("Failed to unregister file type: " + ex.ToString()); retval = int.MinValue; return(false); } } } retval = 0; return(true); }
public WebBrowserOverlayWF(FrameworkElement placementTarget) { _placementTarget = placementTarget; Window owner = Window.GetWindow(placementTarget); Debug.Assert(owner != null); _owner = owner; _form = new Form(); _form.Opacity = owner.Opacity; _form.ShowInTaskbar = false; _form.FormBorderStyle = FormBorderStyle.None; _wb.Dock = DockStyle.Fill; _form.Controls.Add(_wb); //owner.SizeChanged += delegate { OnSizeLocationChanged(); }; owner.LocationChanged += delegate { OnSizeLocationChanged(); }; _placementTarget.SizeChanged += delegate { OnSizeLocationChanged(); }; if (owner.IsVisible) { InitialShow(); } else { owner.SourceInitialized += delegate { InitialShow(); } }; DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(UIElement.OpacityProperty, typeof(Window)); dpd.AddValueChanged(owner, delegate { _form.Opacity = _owner.Opacity; }); _form.FormClosing += delegate { _owner.Close(); }; } void InitialShow() { NativeWindow owner = new NativeWindow(); owner.AssignHandle(((HwndSource)HwndSource.FromVisual(_owner)).Handle); _form.Show(owner); owner.ReleaseHandle(); } DispatcherOperation _repositionCallback; void OnSizeLocationChanged() { // To reduce flicker when transparency is applied without DWM composition, // do resizing at lower priority. if (_repositionCallback == null) { _repositionCallback = _owner.Dispatcher.BeginInvoke(Reposition, DispatcherPriority.Input); } } void Reposition() { _repositionCallback = null; Point offset = _placementTarget.TranslatePoint(new Point(), _owner); Point size = new Point(_placementTarget.ActualWidth, _placementTarget.ActualHeight); HwndSource hwndSource = (HwndSource)HwndSource.FromVisual(_owner); CompositionTarget ct = hwndSource.CompositionTarget; offset = ct.TransformToDevice.Transform(offset); size = ct.TransformToDevice.Transform(size); Win32.POINT screenLocation = new Win32.POINT(offset); Win32.ClientToScreen(hwndSource.Handle, ref screenLocation); Win32.POINT screenSize = new Win32.POINT(size); Win32.MoveWindow(_form.Handle, screenLocation.X, screenLocation.Y, screenSize.X, screenSize.Y, true); //_form.SetBounds(screenLocation.X, screenLocation.Y, screenSize.X, screenSize.Y); //_form.Update(); } }; }
public bool ProcessEvent(IntPtr callref, IntPtr eventref, IntPtr handle, uint kind, ref MSG msg) { IntPtr window = Driver.HandleToWindow(handle); Hwnd hwnd = Hwnd.ObjectFromHandle(window); if (window != IntPtr.Zero) { switch (kind) { case kEventWindowActivated: { Control c = Control.FromHandle(hwnd.client_window); if (c != null) { Form form = c.FindForm(); if (form != null && !form.IsDisposed) { Driver.SendMessage(form.Handle, Msg.WM_ACTIVATE, (IntPtr)WindowActiveFlags.WA_ACTIVE, IntPtr.Zero); XplatUICarbon.ActiveWindow = hwnd.client_window; } } foreach (IntPtr utility_window in XplatUICarbon.UtilityWindows) { if (utility_window != handle && !XplatUICarbon.IsWindowVisible(utility_window)) { XplatUICarbon.ShowWindow(utility_window); } } break; } case kEventWindowExpanding: foreach (IntPtr utility_window in XplatUICarbon.UtilityWindows) { if (utility_window != handle && !XplatUICarbon.IsWindowVisible(utility_window)) { XplatUICarbon.ShowWindow(utility_window); } } msg.hwnd = hwnd.Handle; msg.message = Msg.WM_ENTERSIZEMOVE; return(true); case kEventWindowExpanded: NativeWindow.WndProc(hwnd.Handle, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero); msg.hwnd = hwnd.Handle; msg.message = Msg.WM_EXITSIZEMOVE; return(true); case kEventWindowDeactivated: { Control c = Control.FromHandle(hwnd.client_window); if (c != null) { Form form = c.FindForm(); if (form != null && XplatUICarbon.UnactiveWindow != form.Handle) { Driver.SendMessage(form.Handle, Msg.WM_ACTIVATE, (IntPtr)WindowActiveFlags.WA_INACTIVE, IntPtr.Zero); XplatUICarbon.ActiveWindow = IntPtr.Zero; } } foreach (IntPtr utility_window in XplatUICarbon.UtilityWindows) { if (utility_window != handle && XplatUICarbon.IsWindowVisible(utility_window)) { XplatUICarbon.HideWindow(utility_window); } } break; } case kEventWindowCollapsing: foreach (IntPtr utility_window in XplatUICarbon.UtilityWindows) { if (utility_window != handle && XplatUICarbon.IsWindowVisible(utility_window)) { XplatUICarbon.HideWindow(utility_window); } } msg.hwnd = hwnd.Handle; msg.message = Msg.WM_ENTERSIZEMOVE; return(true); case kEventWindowCollapsed: NativeWindow.WndProc(hwnd.Handle, Msg.WM_WINDOWPOSCHANGED, IntPtr.Zero, IntPtr.Zero); msg.hwnd = hwnd.Handle; msg.message = Msg.WM_EXITSIZEMOVE; return(true); case kEventWindowClose: NativeWindow.WndProc(hwnd.Handle, Msg.WM_CLOSE, IntPtr.Zero, IntPtr.Zero); return(false); case kEventWindowShown: { msg.message = Msg.WM_SHOWWINDOW; msg.lParam = (IntPtr)1; msg.wParam = (IntPtr)0; msg.hwnd = hwnd.Handle; return(true); } case kEventWindowResizeStarted: { msg.message = Msg.WM_ENTERSIZEMOVE; msg.hwnd = hwnd.Handle; return(true); } case kEventWindowResizeCompleted: { msg.message = Msg.WM_EXITSIZEMOVE; msg.hwnd = hwnd.Handle; return(true); } case kEventWindowBoundsChanged: { Rect window_bounds = new Rect(); HIRect view_bounds = new HIRect(); Size size; GetWindowBounds(handle, 33, ref window_bounds); view_bounds.size.width = window_bounds.right - window_bounds.left; view_bounds.size.height = window_bounds.bottom - window_bounds.top; HIViewSetFrame(hwnd.WholeWindow, ref view_bounds); size = XplatUICarbon.TranslateQuartzWindowSizeToWindowSize(Control.FromHandle(hwnd.Handle).GetCreateParams(), (int)view_bounds.size.width, (int)view_bounds.size.height); hwnd.X = (int)window_bounds.left; hwnd.Y = (int)window_bounds.top; hwnd.Width = (int)size.Width; hwnd.Height = (int)size.Height; Driver.PerformNCCalc(hwnd); msg.hwnd = hwnd.Handle; msg.message = Msg.WM_WINDOWPOSCHANGED; Driver.SetCaretPos(XplatUICarbon.Caret.Hwnd, XplatUICarbon.Caret.X, XplatUICarbon.Caret.Y); return(true); } } } return(false); }
public Window2(NativeWindow parent) : base(parent) { }
public static string BrowseForDirectory( IntPtr owner, string initialDirectory = null, string title = null ) { var uiShell = GetService(typeof(SVsUIShell)) as IVsUIShell; if (null == uiShell) { using (var ofd = new FolderBrowserDialog()) { ofd.RootFolder = Environment.SpecialFolder.Desktop; ofd.SelectedPath = initialDirectory; ofd.ShowNewFolderButton = false; DialogResult result; if (owner == IntPtr.Zero) { result = ofd.ShowDialog(); } else { result = ofd.ShowDialog(NativeWindow.FromHandle(owner)); } if (result == DialogResult.OK) { return(ofd.SelectedPath); } else { return(null); } } } if (owner == IntPtr.Zero) { ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner)); } var browseInfo = new VSBROWSEINFOW[1]; browseInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSBROWSEINFOW)); browseInfo[0].pwzInitialDir = initialDirectory; browseInfo[0].pwzDlgTitle = title; browseInfo[0].hwndOwner = owner; browseInfo[0].nMaxDirName = 260; var pDirName = IntPtr.Zero; try { browseInfo[0].pwzDirName = pDirName = Marshal.AllocCoTaskMem(520); var hr = uiShell.GetDirectoryViaBrowseDlg(browseInfo); if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) { return(null); } ErrorHandler.ThrowOnFailure(hr); return(Marshal.PtrToStringAuto(browseInfo[0].pwzDirName)); } finally { if (pDirName != IntPtr.Zero) { Marshal.FreeCoTaskMem(pDirName); } } }
/// <summary> /// Initializes a new instance of the <see cref="DeviceContextEGL"/> class. /// </summary> /// <param name='windowHandle'> /// A <see cref="IntPtr"/> that specifies the window handle used to create the device context. If it is <see cref="IntPtr.Zero"/> /// the surface referenced by this NativeDeviceContext is a minimal PBuffer. /// </param> /// <exception cref='InvalidOperationException'> /// Is thrown when an operation cannot be performed. /// </exception> public DeviceContextEGL(IntPtr windowHandle) { _NativeSurface = new NativeWindow(windowHandle); }
static WinGLContext() { lock (LoadLock) { // Dynamically load opengl32.dll in order to use the extension loading capabilities of Wgl. if (opengl32Handle == IntPtr.Zero) { opengl32Handle = Functions.LoadLibrary(opengl32Name); if (opengl32Handle == IntPtr.Zero) throw new ApplicationException(String.Format("LoadLibrary(\"{0}\") call failed with code {1}", opengl32Name, Marshal.GetLastWin32Error())); Debug.WriteLine(String.Format("Loaded opengl32.dll: {0}", opengl32Handle)); } // We need to create a temp context in order to load // wgl extensions (e.g. for multisampling or GL3). // We cannot rely on OpenTK.Platform.Wgl until we // create the context and call Wgl.LoadAll(). Debug.Print("Creating temporary context for wgl extensions."); using (INativeWindow native = new NativeWindow()) { // Create temporary context and load WGL entry points // First, set a compatible pixel format to the device context // of the temp window WinWindowInfo window = native.WindowInfo as WinWindowInfo; WinGraphicsMode selector = new WinGraphicsMode(window.DeviceContext); SetGraphicsModePFD(selector, GraphicsMode.Default, window); // Then, construct a temporary context and load all wgl extensions ContextHandle temp_context = new ContextHandle(Wgl.Imports.CreateContext(window.DeviceContext)); if (temp_context != ContextHandle.Zero) { // Make the context current. // Note: on some video cards and on some virtual machines, wglMakeCurrent // may fail with an errorcode of 6 (INVALID_HANDLE). The suggested workaround // is to call wglMakeCurrent in a loop until it succeeds. // See https://www.opengl.org/discussion_boards/showthread.php/171058-nVidia-wglMakeCurrent()-multiple-threads // Sigh... for (int retry = 0; retry < 5; retry++) { bool success = Wgl.Imports.MakeCurrent(window.DeviceContext, temp_context.Handle); if (!success) { Debug.Print("wglMakeCurrent failed with error: {0}. Retrying", Marshal.GetLastWin32Error()); System.Threading.Thread.Sleep(10); } else { // wglMakeCurrent succeeded, we are done here! break; } } // Load wgl extensions and destroy temporary context Wgl.LoadAll(); Wgl.Imports.MakeCurrent(IntPtr.Zero, IntPtr.Zero); Wgl.Imports.DeleteContext(temp_context.Handle); } else { Debug.Print("wglCreateContext failed with error: {0}", Marshal.GetLastWin32Error()); } } } }
GraphicsMode SelectGraphicsModeARB(ColorDepth color, int depth, int stencil, int samples, ColorDepth accum, int buffers, bool stereo) { using (INativeWindow native_window = new NativeWindow()) using (IGraphicsContext context = new GraphicsContext(new GraphicsMode(new ColorFormat(), 0, 0, 0, new ColorFormat(), 2, false), native_window.WindowInfo, 1, 0, GraphicsContextFlags.Default)) { WinWindowInfo window = (WinWindowInfo)native_window.WindowInfo; // See http://www.opengl.org/registry/specs/ARB/wgl_pixel_format.txt // for more details Debug.Write("Selecting pixel format (ARB)... "); if (Wgl.Delegates.wglChoosePixelFormatARB == null || Wgl.Delegates.wglGetPixelFormatAttribivARB == null) { Debug.WriteLine("failed"); return(null); } int[] attribs = new int[] { (int)WGL_ARB_pixel_format.AccelerationArb, (int)WGL_ARB_pixel_format.RedBitsArb, (int)WGL_ARB_pixel_format.GreenBitsArb, (int)WGL_ARB_pixel_format.BlueBitsArb, (int)WGL_ARB_pixel_format.AlphaBitsArb, (int)WGL_ARB_pixel_format.ColorBitsArb, (int)WGL_ARB_pixel_format.DepthBitsArb, (int)WGL_ARB_pixel_format.StencilBitsArb, (int)WGL_ARB_multisample.SampleBuffersArb, (int)WGL_ARB_multisample.SamplesArb, (int)WGL_ARB_pixel_format.AccumRedBitsArb, (int)WGL_ARB_pixel_format.AccumGreenBitsArb, (int)WGL_ARB_pixel_format.AccumBlueBitsArb, (int)WGL_ARB_pixel_format.AccumAlphaBitsArb, (int)WGL_ARB_pixel_format.AccumBitsArb, (int)WGL_ARB_pixel_format.DoubleBufferArb, (int)WGL_ARB_pixel_format.StereoArb, 0 }; int[] values = new int[attribs.Length]; int[] attribs_values = new int[] { (int)WGL_ARB_pixel_format.AccelerationArb, (int)WGL_ARB_pixel_format.FullAccelerationArb, (int)WGL_ARB_pixel_format.DrawToWindowArb, 1, (int)WGL_ARB_pixel_format.RedBitsArb, color.Red, (int)WGL_ARB_pixel_format.GreenBitsArb, color.Green, (int)WGL_ARB_pixel_format.BlueBitsArb, color.Blue, (int)WGL_ARB_pixel_format.AlphaBitsArb, color.Alpha, (int)WGL_ARB_pixel_format.ColorBitsArb, color.BitsPerPixel - color.Alpha, // Should not contain alpha bpp (see spec) (int)WGL_ARB_pixel_format.DepthBitsArb, depth, (int)WGL_ARB_pixel_format.StencilBitsArb, stencil, (int)WGL_ARB_multisample.SampleBuffersArb, samples > 0 ? 1 : 0, (int)WGL_ARB_multisample.SamplesArb, samples, (int)WGL_ARB_pixel_format.AccumRedBitsArb, accum.Red, (int)WGL_ARB_pixel_format.AccumGreenBitsArb, accum.Green, (int)WGL_ARB_pixel_format.AccumBlueBitsArb, accum.Blue, (int)WGL_ARB_pixel_format.AccumAlphaBitsArb, accum.Alpha, (int)WGL_ARB_pixel_format.AccumBitsArb, accum.BitsPerPixel, // Spec doesn't mention wether alpha bpp should be included... (int)WGL_ARB_pixel_format.DoubleBufferArb, buffers > 1 ? 1 : 0, (int)WGL_ARB_pixel_format.StereoArb, stereo ? 1 : 0, 0, 0 }; int[] pixel = new int[1], num_formats = new int[1]; bool success = Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, null, 1, pixel, num_formats); if (!success || num_formats[0] == 0 || pixel[0] == 0) { // Try again without an accumulator. Many modern cards cannot accelerate multisampled formats with accumulator buffers. int index_of_accum = Array.IndexOf(attribs_values, (int)WGL_ARB_pixel_format.AccumRedBitsArb); attribs_values[index_of_accum + 1] = attribs_values[index_of_accum + 3] = attribs_values[index_of_accum + 5] = attribs_values[index_of_accum + 7] = attribs_values[index_of_accum + 9] = 0; Wgl.Arb.ChoosePixelFormat(window.DeviceContext, attribs_values, null, 1, pixel, num_formats); } if (!success || num_formats[0] == 0 || pixel[0] == 0) { Debug.WriteLine("failed (no suitable pixel format)."); return(null); } // Find out what we really got as a format: success = Wgl.Arb.GetPixelFormatAttrib(window.DeviceContext, pixel[0], 0, attribs.Length - 1, attribs, values); if (!success) { Debug.WriteLine("failed (pixel format attributes could not be determined)."); return(null); } GraphicsMode mode = new GraphicsMode(new IntPtr(pixel[0]), new ColorDepth(values[1], values[2], values[3], values[4]), values[6], values[7], values[8] != 0 ? values[9] : 0, new ColorDepth(values[10], values[11], values[12], values[13]), values[15] == 1 ? 2 : 1, values[16] == 1 ? true : false); Debug.WriteLine("success!"); return(mode); } }
public static void Main(string[] args) { try { using (var container = new ServiceContainer()) using (var window = new NativeWindow()) { window.Title = "Vulkan Example - Basic indexed triangle"; window.Visible = true; container.RegisterInstance <INativeWindow>(window); // Magnesium container.Register <Magnesium.MgDriverContext>(new PerContainerLifetime()); container.Register <Magnesium.IMgPresentationSurface, Magnesium.PresentationSurfaces.OpenTK.VulkanPresentationSurface>(new PerContainerLifetime()); container.Register <Magnesium.IMgGraphicsConfiguration, Magnesium.MgDefaultGraphicsConfiguration>(new PerContainerLifetime()); container.Register <Magnesium.IMgImageTools, Magnesium.MgImageTools>(new PerContainerLifetime()); // Magnesium.VUlkan container.Register <TriangleDemo.ITriangleDemoShaderPath, SPIRVTriangleShaderPath>(new PerContainerLifetime()); container.Register <Magnesium.IMgEntrypoint, Magnesium.Vulkan.VkEntrypoint>(new PerContainerLifetime()); // SCOPE container.Register <Magnesium.IMgGraphicsDevice, Magnesium.MgDefaultGraphicsDevice>(new PerScopeLifetime()); container.Register <VulkanExample>(new PerScopeLifetime()); container.Register <Magnesium.IMgPresentationBarrierEntrypoint, Magnesium.MgPresentationBarrierEntrypoint>(new PerScopeLifetime()); container.Register <Magnesium.IMgPresentationLayer, Magnesium.MgPresentationLayer>(new PerScopeLifetime()); container.Register <Magnesium.IMgSwapchainCollection, Magnesium.MgSwapchainCollection>(new PerScopeLifetime()); using (var scope = container.BeginScope()) { using (var driver = container.GetInstance <MgDriverContext>()) { driver.Initialize( new MgApplicationInfo { ApplicationName = "Vulkan Example", ApiVersion = Magnesium.MgApplicationInfo.GenerateApiVersion(1, 0, 17), ApplicationVersion = 1, EngineName = "Magnesium", EngineVersion = 1, }, MgInstanceExtensionOptions.ALL); using (var graphicsConfiguration = container.GetInstance <IMgGraphicsConfiguration>()) { using (var secondLevel = container.BeginScope()) { using (var gameWindow = new GameWindow(window)) using (var example = container.GetInstance <VulkanExample>()) { gameWindow.RenderFrame += (sender, e) => { example.RenderLoop(); }; gameWindow.Run(60, 60); } } } } } } } catch (Exception ex) { Console.WriteLine(ex); } }
internal virtual void WindowDidEndLiveResize(object sender, EventArgs e) { NativeWindow.WndProc(ContentView.Handle, Msg.WM_EXITSIZEMOVE, IntPtr.Zero, IntPtr.Zero); }
public OpenTK(NativeWindow window) { window.KeyPress += KeyPress; }
public void NativeWindow_Ctor_Default() { var window = new NativeWindow(); Assert.Equal(IntPtr.Zero, window.Handle); }
protected override void OnInitialized( ) { NativeWindow.SetBackground(Background.R, Background.G, Background.B, Background.A); }
/// <summary> /// Constructs a new instance of a CopyData channel. Called /// automatically by the CopyDataChannels collection. /// </summary> /// <param name="owner">The owning native window</param> /// <param name="channelName">The name of the channel to /// send messages on</param> internal CopyDataChannel(NativeWindow owner, string channelName) { this.owner = owner; this.channelName = channelName; addChannel(); }
public static string BrowseForFileOpen(this IServiceProvider serviceProvider, IntPtr owner, string filter, string initialPath = null) { if (string.IsNullOrEmpty(initialPath)) { initialPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar; } IVsUIShell uiShell = serviceProvider.GetService(typeof(SVsUIShell)) as IVsUIShell; if (null == uiShell) { using (var sfd = new System.Windows.Forms.OpenFileDialog()) { sfd.AutoUpgradeEnabled = true; sfd.Filter = filter; sfd.FileName = Path.GetFileName(initialPath); sfd.InitialDirectory = Path.GetDirectoryName(initialPath); DialogResult result; if (owner == IntPtr.Zero) { result = sfd.ShowDialog(); } else { result = sfd.ShowDialog(NativeWindow.FromHandle(owner)); } if (result == DialogResult.OK) { return(sfd.FileName); } else { return(null); } } } if (owner == IntPtr.Zero) { ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner)); } VSOPENFILENAMEW[] openInfo = new VSOPENFILENAMEW[1]; openInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW)); openInfo[0].pwzFilter = filter.Replace('|', '\0') + "\0"; openInfo[0].hwndOwner = owner; openInfo[0].nMaxFileName = 260; var pFileName = Marshal.AllocCoTaskMem(520); openInfo[0].pwzFileName = pFileName; openInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath); var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray(); Marshal.Copy(nameArray, 0, pFileName, nameArray.Length); try { int hr = uiShell.GetOpenFileNameViaDlg(openInfo); if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) { return(null); } ErrorHandler.ThrowOnFailure(hr); return(Marshal.PtrToStringAuto(openInfo[0].pwzFileName)); } finally { if (pFileName != IntPtr.Zero) { Marshal.FreeCoTaskMem(pFileName); } } }
public void setScreenTarget(NativeWindow NW) { }
/// <summary> /// Calling this method is identical to calling the ShowDialog method of the provided /// FolderBrowserDialog, except that an attempt will be made to scroll the Tree View /// to make the currently selected folder visible in the dialog window. /// </summary> /// <param name="dlg"></param> /// <param name="parent"></param> /// <returns></returns> public static bool?ShowFolderBrowser(this FolderBrowserDialog dlg, Window owner = null) { DialogResult result = DialogResult.Cancel; int retries = 40; NativeWindow parent = null; if (owner != null) { parent = new NativeWindow(); parent.AssignHandle(new WindowInteropHelper(owner).Handle); } try { if (dlg.SelectedPath != "") { dlg.SelectedPath = System.IO.Path.GetFullPath(dlg.SelectedPath); } } catch { } using (Timer t = new Timer()) { t.Tick += (s, a) => { if (retries > 0) { --retries; IntPtr hwndDlg = FindWindow((string)null, _topLevelSearchString); if (hwndDlg != IntPtr.Zero) { IntPtr hwndFolderCtrl = GetDlgItem(hwndDlg, _dlgItemBrowseControl); if (hwndFolderCtrl != IntPtr.Zero) { IntPtr hwndTV = GetDlgItem(hwndFolderCtrl, _dlgItemTreeView); if (hwndTV != IntPtr.Zero) { IntPtr item = SendMessage(hwndTV, (uint)TVM_GETNEXTITEM, new IntPtr(TVGN_CARET), IntPtr.Zero); if (item != IntPtr.Zero) { // Let's send this 40 times until we drill it into the folder browser's thick skull. // Otherwise it will just go back to the beginning. SendMessage(hwndTV, TVM_ENSUREVISIBLE, IntPtr.Zero, item); //retries = 0; //t.Stop(); } } } } } else { // // We failed to find the Tree View control. // // As a fall back (and this is an UberUgly hack), we will send // some fake keystrokes to the application in an attempt to force // the Tree View to scroll to the selected item. // t.Stop(); //SendKeys.Send("{TAB}{TAB}{DOWN}{DOWN}{UP}{UP}"); } }; t.Interval = 10; t.Start(); result = dlg.ShowDialog(parent); }; return(result == DialogResult.OK); }
public void Run() { Window = new NativeWindow(640, 400, Program.AppName, GraphicsMode.Default, DisplayDevice.Primary); Window.Visible = true; Drawer = new GdiPlusDrawer2D(); Init(); TryLoadTexturePack(); platformDrawer.info = Window.WindowInfo; platformDrawer.Init(); fetcher = new ResourceFetcher(); fetcher.CheckResourceExistence(); checkTask = new UpdateCheckTask(); checkTask.CheckForUpdatesAsync(); if (!fetcher.AllResourcesExist) { SetScreen(new ResourcesScreen(this)); } else { SetScreen(new MainScreen(this)); } while (true) { Window.ProcessEvents(); if (!Window.Exists) { break; } if (ShouldExit) { if (Screen != null) { Screen.Dispose(); } break; } Screen.Tick(); if (Dirty) { Display(); } Thread.Sleep(10); } if (Options.Load()) { LauncherSkin.SaveToOptions(); Options.Save(); } if (ShouldUpdate) { Updater.Applier.ApplyUpdate(); } if (Window.Exists) { Window.Close(); } }
private IWin32Window GetNativeWindow() { return(NativeWindow.FromHandle(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle)); }
public NativeMessageBox.Result Show(string text, string caption, NativeMessageBox.Type messageBoxType, NativeWindow childWindow) { IntPtr messagePtr = IntPtr.Zero; if (childWindow != null) { NativeWindow_Windows winInterface = childWindow.GetInterface() as NativeWindow_Windows; UnityEngine.Debug.Assert(winInterface != null); messagePtr = winInterface.windowPtr; } int result = MessageBox(messagePtr, text.ToString(), caption.ToString(), (uint)messageBoxType); return((NativeMessageBox.Result)result); }
private WindowTreeNode AddWindow(IntPtr hwnd, bool isManaged) { WindowTreeNode node = new WindowTreeNode(hwnd, isManaged); if (!isManaged) { NativeWindow native = new NativeWindow(); native.Handle = hwnd; native.ClassName = node.WindowClassName; native.Text = node.WindowText; node.Tag = native; } if (!hwndNodeMap.ContainsKey(hwnd)) hwndNodeMap[hwnd] = node; return node; }