void inkCol_Stroke(object sender, InkCollectorStrokeEventArgs e) { //if the stroke doesn't already have a timestamp, add one if (!e.Stroke.ExtendedProperties.DoesPropertyExist(Microsoft.Ink.StrokeProperty.TimeID)) { try { //Retrieve the current time. UTC format. DateTime dt = DateTime.Now; long filetime = dt.ToFileTime(); MemoryStream memstr = new MemoryStream(); BinaryWriter binwrite = new BinaryWriter(memstr); binwrite.Write(filetime); Byte[] bt = memstr.ToArray(); memstr.Close(); binwrite.Close(); e.Stroke.ExtendedProperties.Add(Microsoft.Ink.StrokeProperty.TimeID, bt); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
void ic_Stroke(object sender, InkCollectorStrokeEventArgs e) { rct.StopBackgroundRecognition(); rct.Strokes.Add(e.Stroke); //rct.CharacterAutoCompletion = RecognizerCharacterAutoCompletionMode.Prefix; rct.BackgroundRecognizeWithAlternates(0); }
/// <summary> /// Event Handle from Stroke event /// </summary> /// <param name="sender">The control that raised the event.</param> /// <param name="e">The event arguments.</param> public void myInkCollector_Stroke(object sender, InkCollectorStrokeEventArgs e) { if (e.Cursor.Inverted) { e.Cancel = true; } }
/// <summary> /// Event Handler from Ink Overlay's Stroke event /// This event is fired when a new stroke is drawn. /// In this case, it is necessary to update the ink divider's /// strokes collection. The event is fired even when the eraser stroke is created. /// The event handler must filter out the eraser strokes. /// </summary> /// <param name="sender">The control that raised the event.</param> /// <param name="e">The event arguments.</param> private void myInkOverlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { // Filter out the eraser stroke. if (InkOverlayEditingMode.Ink == myInkOverlay.EditingMode) { // Add the new stroke to the ink divider's strokes collection myInkDivider.Strokes.Add(e.Stroke); if (miAutomaticLayoutAnalysis.Checked) { // Call DivideInk DivideInk(); // Repaint the screen to reflect the change DrawArea.Refresh(); } } }
/*------------------------------------------------------------------------------------*/ /*----------------------Implementation of Ink Stoke Event Handler----------------------*/ void drawingArea_Stroke(object sender, InkCollectorStrokeEventArgs e) { //RecognizeStroke(drawingArea); if (firstInkStroke) { firstInkStroke = false; Strokes tmpStrokes = drawingArea.Ink.CreateStrokes(); string collectionName = "Collection" + collectionCounter; drawingArea.Ink.CustomStrokes.Add(collectionName, tmpStrokes); drawingArea.Ink.CustomStrokes[collectionName].Add(e.Stroke); timeToDraw.Enabled = true; } else { drawingArea.Ink.CustomStrokes[getCollectionName()].Add(e.Stroke); } }
void m_InkPicture_Stroke(object sender, InkCollectorStrokeEventArgs e) { m_Move = null; e.Cancel = true; InkPicture ip = sender as InkPicture; Graphics g = null; lock (ip.Image) { g = Graphics.FromImage(ip.Image); } List <ICorner> corners = new List <ICorner>(); foreach (Point p in e.Stroke.GetPoints()) { Point clientP = StrokePointToClientPoint(g, p); ICorner c = m_GameBoard.ClosestCornerFromGraphicsPoint(clientP); if (!corners.Contains(c)) { corners.Add(c); } } if (corners.Count == 2) { try { Line l = new Line(corners[0] as Corner, corners[1] as Corner); m_Move = new Move(l, this); } catch (ArgumentException) { /* the line sucks - eat it */ } } m_Waiter.Set(); }
void m_InkPicture_Stroke(object sender, InkCollectorStrokeEventArgs e) { m_Move = null; e.Cancel = true; InkPicture ip = sender as InkPicture; Graphics g = null; lock (ip.Image) { g = Graphics.FromImage(ip.Image); } List<ICorner> corners = new List<ICorner>(); foreach (Point p in e.Stroke.GetPoints()) { Point clientP = StrokePointToClientPoint(g, p); ICorner c = m_GameBoard.ClosestCornerFromGraphicsPoint(clientP); if (!corners.Contains(c)) { corners.Add(c); } } if (corners.Count == 2) { try { Line l = new Line(corners[0] as Corner, corners[1] as Corner); m_Move = new Move(l, this); } catch (ArgumentException) { /* the line sucks - eat it */ } } m_Waiter.Set(); }
private void inkOverlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { Strokes strokes = null; Ink copiedInk = null; try { // Eraser strokes are transparent, we don't need to send them if (e.Stroke.DrawingAttributes.Transparency != 255) { // Give the stroke an identifier, so we can delete it remotely e.Stroke.ExtendedProperties.Add(StrokeIdentifier, Guid.NewGuid().ToString()); // Copy the stroke into its own Ink object, so that it can be serialized strokes = inkOverlay.Ink.CreateStrokes(new int[] { e.Stroke.Id }); copiedInk = e.Stroke.Ink.ExtractStrokes(strokes, ExtractFlags.CopyFromOriginal); // Send it across the network wb.SendObject(new SerializedInk(copiedInk)); } } catch (Exception ex) { Log(ex.ToString()); } finally { if (strokes != null) { strokes.Dispose(); } if (copiedInk != null) { copiedInk.Dispose(); } } }
public void run() { System.Threading.Thread.CurrentThread.Priority = ThreadPriority.Highest; try { bool clientTalking = true; //a loop that reads from and writes to the socket while (clientTalking) { //get what client wants to say... byte[] bytes = new byte[8192]; // 8 KB de dados int bytesRec = this.socket.Receive(bytes); // System.Diagnostics.Debug.WriteLine("----- Recebido... -----"); ArrayList list = (ArrayList) getObjectWithByteArray(bytes); Object o = list[0]; String nomeEvento = (String) list[1]; // EVENTOS DO ARGO if (nomeEvento.Equals("PROT_atualiza_modelo_cliente")) { } if (nomeEvento.Equals("PROT_atualiza_modelo_cliente_inicial")) { ArrayList ListDoc = (ArrayList) o; // Global.main.OpenForCollaboration( ); Global.main.Invoke(new MainForm.DelegateOpenMetod(Global.main.OpenForCollaboration) ,new object[] { (TextWriter) ListDoc[0] }); } // Recebeu a notificação que algum cliente entrou na da sessão! if (nomeEvento.Equals("PROT_inicio_sessao")) { } // Recebeu a notificação que algum cliente saiu da sessão! if (nomeEvento.Equals("PROT_fim_sessao")) { } // Esta ação foi removida para a experiência /* if (nomeEvento.equals("ActionDeleteFromDiagram-actionPerformed")) ActionDeleteFromDiagram.SINGLETON.actionPerformedImpl((ActionEvent) o); */ // EVENTOS DO GEF // Desenho do TelePointer! #region mouseMovedPointer if (nomeEvento.Equals("mouseMovedPointer")) { /* // Sem os telePointers por enquanto ArrayList dados = (ArrayList) o; FigPointer fp = Global.main.fpA; String Id_tele = (String) dados[2]; if (Id_tele.Equals("1") ) fp = Global.main.fpA; if (Id_tele.Equals("2") ) fp = Global.main.fpB; if (Id_tele.Equals("3") ) fp = Global.main.fpC; if (Id_tele.Equals("4") ) fp = Global.main.fpD; fp.setCor((Color) dados[1] ); fp.setNome((String) dados[3]); fp.setLocation((Point) dados[0]); */ } #endregion #region inkoverlay_Stroke if (nomeEvento.Equals("inkoverlay_Stroke")) { ArrayList dados = (ArrayList) o; Ink x = new Ink(); x.Load( (byte[]) dados[0] ); Stroke s = x.Strokes[x.Strokes.Count-1]; // Testes: Adicionando a coleção de strokes! Global.main.doc.Ink.CreateStroke(s.GetPoints()); InkCollectorStrokeEventArgs e = new InkCollectorStrokeEventArgs(null ,s , false); // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateToMethod(Global.main.inkoverlay_StrokeImpl),new object[] { e }); } #endregion #region inkoverlay_StrokesDeleting if (nomeEvento.Equals("inkoverlay_StrokesDeleting")) { ArrayList dados = (ArrayList) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.inkoverlay_StrokesDeletingImpl),new object[] { dados }); } #endregion #region inkoverlay_SelectionMovedOrResized if (nomeEvento.Equals("inkoverlay_SelectionMovedOrResized")) { ArrayList dados = (ArrayList) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.inkoverlay_SelectionMovedOrResizedImpl),new object[] { dados }); } #endregion #region hover_EditCloneClicked if (nomeEvento.Equals("hover_EditCloneClicked")) { ArrayList dados = (ArrayList) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.hover_EditCloneClickedImpl),new object[] { dados }); } #endregion #region hover_EditStraightenClicked if (nomeEvento.Equals("hover_EditStraightenClicked")) { ArrayList dados = (ArrayList) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.hover_EditStraightenClickedImpl),new object[] { dados }); } #endregion #region hover_EditPropertiesClicked if (nomeEvento.Equals("hover_EditPropertiesClicked")) { ArrayList dados = (ArrayList) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.hover_EditPropertiesClickedImpl),new object[] { dados }); } #endregion // Controles da simulação remota #region hover_AnimateClicked_Start if (nomeEvento.Equals("Start")) { // É preciso criar outra Thread aqui para continuar recebendo os dados.... // E depois é preciso terminá-la cr = new ClienteRecebe(this.socket); ThreadStart threadDelegate = new ThreadStart(cr.run); Thread tClienteRecebe = new Thread(threadDelegate); tClienteRecebe.Start(); Object dados = (Object) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedStartImpl),new object[] { dados }); /* tClienteRecebe.Abort(); Thread.Sleep(5); cr = null; */ } #endregion #region hover_AnimateClicked_Stop if (nomeEvento.Equals("Stop")) { Object dados = (Object) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedStopImpl),new object[] { dados }); // System.Threading.Thread.CurrentThread.Abort(); // É preciso cometer suicídio, ou seja, essa Thread deve se auto-terminar if(cr != null) return; } #endregion #region hover_AnimateClicked_Pause if (nomeEvento.Equals("Pause")) { Object dados = (Object) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedPauseImpl) ,new object[] { dados }); } #endregion #region hover_AnimateClicked_Resume if (nomeEvento.Equals("Resume")) { Object dados = (Object) o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedResumeImpl) ,new object[] { dados }); } #endregion } } catch (ThreadAbortException e) { MessageBox.Show("ThreadAbortException in ClienteRecebe:" + e.Message , Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } catch (Exception e) { MessageBox.Show("Exception in ClienteRecebe:" + e.Message , Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
/// <summary> /// Fragment the loaded Stroke at the intersections created by the drawn /// Microsoft.Ink.Stroke. /// </summary> /// <param name="sender">Reference to the object that raised the event</param> /// <param name="e">Passes an object specific to the event that is being handled</param> private void sketchInk_Stroke(object sender, InkCollectorStrokeEventArgs e) { // Find the float intersection points float[] intersections = e.Stroke.FindIntersections(sketchInk.Ink.Strokes); System.Drawing.Point[] pointInter = new System.Drawing.Point[intersections.Length]; // Find the actual points of intersection for (int i = 0; i < pointInter.Length; ++i) { pointInter[i] = LocatePoint(e.Stroke, intersections[i]); } // Remove our drawing stroke from the Ink this.sketchInk.Ink.DeleteStroke(e.Stroke); // Threshold for how far away we can draw from the actual stroke const double DISTTHRESHOLD = 40.0; // Hashtable mapping new points to FeatureStrokes Dictionary <Sketch.Stroke, List <int> > ptsToAdd = new Dictionary <Sketch.Stroke, List <int> >(); // For each point in our intersections we'll find the closest point in // the corresponding FeatureStroke points foreach (System.Drawing.Point currPt in pointInter) { int bestPointIndex = 0; double bestDist = Double.PositiveInfinity; Sketch.Stroke bestStroke = null; // Check all of the FeatureStrokes to see if the Point is close enough foreach (Sketch.Stroke stroke in this.strokes) { Sketch.Point[] pts = stroke.Points; // Find the closest point for this FeatureStroke for (int i = 0; i < pts.Length; i++) { double currDist = Euclidean(currPt.X, currPt.Y, pts[i].X, pts[i].Y); if (currDist < bestDist) { bestDist = currDist; bestPointIndex = i; bestStroke = stroke; } } } // If it's close enough, add it to our temporary Hashtable to keep track of // which point corresponds to which FeatureStroke if (bestDist < DISTTHRESHOLD) { bool alreadyExists = false; if (this.strokeToCorners.ContainsKey(bestStroke)) { List <int> existingPts = this.strokeToCorners[bestStroke]; if (existingPts.Contains(bestPointIndex)) { alreadyExists = true; } } if (!alreadyExists) { if (!ptsToAdd.ContainsKey(bestStroke)) { List <int> newPts = new List <int>(); newPts.Add(bestPointIndex); ptsToAdd.Add(bestStroke, newPts); } else { List <int> existingPts = ptsToAdd[bestStroke]; if (!existingPts.Contains(bestPointIndex)) { existingPts.Add(bestPointIndex); } } } } } if (ptsToAdd.Count > 0) { // Hand-fragment the stroke CM.ExecuteCommand(new CommandList.HandFragmentCornersCmd(ptsToAdd, this.strokeToCorners, this.overlayInk, this.fragmentPtAttributes)); } sketchInk.Refresh(); }
/// <summary> /// Event Handle from Stroke event /// </summary> /// <param name="sender">The control that raised the event.</param> /// <param name="e">The event arguments.</param> public void myInkCollector_Stroke(object sender, InkCollectorStrokeEventArgs e ) { if (e.Cursor.Inverted) { e.Cancel = true; } }
/// <summary> /// Resizes InkPicture when necessary (for scrolling) /// </summary> protected void inkPic_Stroke(object sender, InkCollectorStrokeEventArgs e) { this.resizeInkPicture(); updateFocus(); }
public void inkoverlay_StrokeImpl(InkCollectorStrokeEventArgs e) { dbg.WriteLine("----- inkoverlay_StrokeImpl -----"); // Previso verificar o modo. Se estiver em um modo que não seja a edição, salva // o modo atual e coloca na edição. No final volto ao modo que estava // Primeiro passo é salvar o modo de edição autal e colocar no modo de deleção InkOverlayEditingMode em = inkoverlay.EditingMode; SetEditingMode(InkOverlayEditingMode.Ink,true); try // To prevent exceptions from propagating back to ink runtime. { /* // Hook for tap-to-select feature, in lasso-mode. if (inkoverlay.EditingMode == InkOverlayEditingMode.Select) { //////////////// USO DO STROKE ////////////////////// TryTapToSelect(e.Stroke); return; } */ // Analyze stroke geometry. bool closed; Point[] vertices; double tolerance = 500.0; //Heuristic: 500 seems about right. //////////////// USO DO STROKE ////////////////////// StrokeAnalyzer.AnalyzeClosedness(e.Stroke, tolerance, out closed, out vertices); // Se for um desenho fechado... // Interpret stroke in document-context: first, consider closed strokes. if (closed) { // Check for a small elliptical-gesture over two or more bodies. // If so, it's a pin joint! //////////////// USO DO STROKE ////////////////////// Rectangle bbox = e.Stroke.GetBoundingBox(); Point midp = Geometry.Midpoint(bbox); RigidBodyBase[] hits = doc.HitTestBodies(midp); if (hits.Length >= 2 && bbox.Width < 1000 && bbox.Height < 1000) { RigidBodyBase top = hits[0]; RigidBodyBase bottom = hits[1]; // Snap to CG if close to either top's or bottom's. if (Geometry.DistanceBetween(midp,top.CG) < 500.0) midp = top.CG; else if (Geometry.DistanceBetween(midp,bottom.CG) < 500.0) midp = bottom.CG; dbg.WriteLine("new JointMech"); JointMech newmech = new JointMech(); newmech.EndpointA = BodyRef.For(bottom,midp); newmech.EndpointB = BodyRef.For(top,midp); //////////////// USO DO STROKE ////////////////////// newmech.strokeid = e.Stroke.Id; doc.Mechanisms.Add(newmech); // Repaint area around the newmech (unions with stroke bbox, below). Rectangle dirtybbox = newmech.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); return; } else { // Larger stroke, and/or no centerpoint hits -- form a new solid body. //////////////// USO DO STROKE ////////////////////// RigidBodyBase newbody = MakeBodyFromClosedStroke(e.Stroke,vertices); // Repaint area around the newbody (unions with stroke bbox, below). Rectangle dirtybbox = newbody.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); // Select it, to show the smart tag. //////////////// USO DO STROKE ////////////////////// // TESTE: Retirada da selecion // TESTE: inkoverlay.Selection = this.MakeSingleStrokeCollection(e.Stroke); // inkoverlay.Selection = this.MakeSingleStrokeCollectionImpl(); return; } } // Caso senha um desenho aberto... // An unclosed stroke -- // Check if head and/or tail is hit on existing bodies. //////////////// USO DO STROKE ////////////////////// int np = e.Stroke.PacketCount; Point head = e.Stroke.GetPoint(0), tail = e.Stroke.GetPoint(np-1); RigidBodyBase[] headhits = doc.HitTestBodies(head); RigidBodyBase[] tailhits = doc.HitTestBodies(tail); if (headhits.Length == 0 && tailhits.Length == 0) { // Neither head or tail hit, so let's try harder to make a body // out of this stroke. Point[] dummy; tolerance = 2000.0; //Heuristic: vastly relax closure tolerance. //////////////// USO DO STROKE ////////////////////// StrokeAnalyzer.AnalyzeClosedness(e.Stroke, tolerance, out closed, out dummy); if (closed) { //////////////// USO DO STROKE ////////////////////// RigidBodyBase newbody = MakeBodyFromClosedStroke(e.Stroke,vertices); // Repaint area around the newbody (unions with stroke bbox, below). Rectangle dirtybbox = newbody.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); // Select it, to show the smart tag. //////////////// USO DO STROKE ////////////////////// // TESTE: Retirada da selecion // inkoverlay.Selection = this.MakeSingleStrokeCollection(e.Stroke); return; } else if (Geometry.DistanceBetween(head,tail) > 500.0) { // Interpret this stroke as a gravity-vector. GravitationalForceMech newgrav = new GravitationalForceMech(); newgrav.Body = null; // Applies to all bodies! newgrav.origin = head; newgrav.vector = Vector.FromPoints(head,tail); // Repaint area around the gravity vector (unions with stroke bbox, below). Rectangle dirtybbox = newgrav.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); // Throw out the current gravity-vector stroke, if it exists. if (doc.Gravity != null) { dirtybbox = doc.Gravity.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); // Testes de remoçao do Gravity Strike if(doc.Ink.Strokes.Count > 0) { foreach (Stroke S in doc.Ink.Strokes) { if (S.Id == doc.Gravity.strokeid) { doc.Ink.DeleteStroke(S); } } } } //////////////// USO DO STROKE ////////////////////// newgrav.strokeid = e.Stroke.Id; doc.Gravity = newgrav; return; } else { // This stroke is probably an accidental tap -- discard it. e.Cancel = true; return; } } if (headhits.Length > 0 && tailhits.Length == 0) { // If only the head is hit, it must be an 'attractive force'. RigidBodyBase body = headhits[0]; dbg.WriteLine("new ExternalForceMech"); ExternalForceMech newmech = new ExternalForceMech(); newmech.Body = BodyRef.For(body,head); newmech.vector = Vector.FromPoints(head,tail); //////////////// USO DO STROKE ////////////////////// newmech.strokeid = e.Stroke.Id; doc.Mechanisms.Add(newmech); // Repaint area around the newmech (unions with stroke bbox, below). Rectangle dirtybbox = newmech.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); return; } if (headhits.Length == 0 && tailhits.Length > 0) { // If only the tail is hit, it must be a 'propulsive force'. RigidBodyBase body = tailhits[0]; dbg.WriteLine("new PropulsiveForceMech"); PropulsiveForceMech newmech = new PropulsiveForceMech(); newmech.Body = BodyRef.For(body,tail); newmech.vector = Vector.FromPoints(head,tail); //////////////// USO DO STROKE ////////////////////// newmech.strokeid = e.Stroke.Id; doc.Mechanisms.Add(newmech); // Repaint area around the newmech (unions with stroke bbox, below). Rectangle dirtybbox = newmech.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); return; } if (true) // scope { // Create a binding mechanism between two bodies. RigidBodyBase headbody = headhits[0], tailbody = tailhits[0]; // If both the head and the tail hit same object, // attach the head to the one behind. if (Object.ReferenceEquals(headbody,tailbody)) { if (headhits.Length > 1) headbody = headhits[1]; else if (tailhits.Length > 1) tailbody = tailhits[1]; else { // Aqui é feita a seleção. Remotamente não faço nada // Don't self-connect. We will perhaps interpret the stroke as an // anchor-gesture or a selection-gesture, // but if we cannot, we will cancel. //////////////// USO DO STROKE ////////////////////// int nc = e.Stroke.PolylineCusps.Length; if (np <= 25) { // TESTE: Retirada da selecion // inkoverlay.Selection = MakeSingleStrokeCollection(headbody.strokeid); SetEditingMode(InkOverlayEditingMode.Select,false); } else if (np <= 150 && (nc >= 3 && nc <= 5)) { headbody.anchored = !headbody.anchored; //toggle } e.Cancel = true; // Repaint area around the headbody (unions with stroke bbox, below). Rectangle dirtybbox = headbody.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); return; } } // Create a rope, rod, or spring out of the stroke. //////////////// USO DO STROKE ////////////////////// MechanismBase newmech = MakeRodRopeOrSpring(e.Stroke,headbody,tailbody); if (newmech != null) { // Repaint area around the newmech (unions with stroke bbox, below). Rectangle dirtybbox = newmech.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); return; } else { // Throw out the stroke, and return. e.Cancel = true; return; } } } catch (Exception ex) { // Cancel the stroke, and log the error. e.Cancel = true; Global.HandleThreadException(this, new System.Threading.ThreadExceptionEventArgs(ex)); } finally { // Repaint the area around the stroke (unions with newbody/mech region, above). //////////////// USO DO STROKE ////////////////////// Rectangle dirtybbox = e.Stroke.GetBoundingBox(); InvalidateInkSpaceRectangle(dirtybbox); SetEditingMode(em,true); } }
/// <summary> /// Stroke event handler fired when a stroke is just finished. /// </summary> /// <remarks>Notice that even if we use a InkOverlay object and not a InkCollector /// object, the second input parameter is of type InkCollectorStrokeEventArgs</remarks> /// <param name="sender">Event sender</param> /// <param name="e">Event arguments (type InkCollectorStrokeEventArgs)</param> private void inkOverlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { if (e.Stroke.DrawingAttributes.Transparency != 255) { Log("A stroke has been drawn!"); // Resize the stroke before sending Log("Resize the stroke,"); DisplaySizeInfo(); Microsoft.Ink.Strokes strokes = inkOverlay.Ink.CreateStrokes(); strokes.Add(e.Stroke); Microsoft.Ink.Ink newInk = new Microsoft.Ink.Ink(); newInk.AddStrokesAtRectangle(strokes, strokes.GetBoundingBox()); Microsoft.Ink.Stroke copiedStroke = newInk.Strokes[0]; // Note: rtDocument.Resources.Pages[pageShowing].Image.Width cannot be // used here because it's 5760 when open a PPT document // Ditto for rtDocument.Resources.Pages[pageShowing].Image.Height, // the value is 4320 float ratioWidthSend = (float)constWidthPageSend/(float)pbRTDoc.Width; float ratioHeightSend = (float)constHeightPageSend/(float)pbRTDoc.Height; Log(string.Format(CultureInfo.CurrentCulture, "RatioWidthSend={0}, RatioHeightSend={1}, ", ratioWidthSend.ToString(CultureInfo.InvariantCulture), ratioHeightSend.ToString(CultureInfo.InvariantCulture))); copiedStroke.Scale(ratioWidthSend, ratioHeightSend); // Send the resized stroke Log("Send a resized stroke,"); rtDocumentHelper.SendStrokeAdd(copiedStroke); // Copy the guid in the extendend property generated inside copieStroke // by rtDocumentHelper.BeginSendStrokeAdd in the extended property of the // local stroke // Note: it is very important to do that because when the user // delete a stroke, the stroke guid of the local and remote // stroke must match (copieStroke is the stroke that is sent, // e.Stroke is the local stroke) e.Stroke.ExtendedProperties.Add(RTStroke.ExtendedPropertyStrokeIdentifier, copiedStroke.ExtendedProperties[RTStroke.ExtendedPropertyStrokeIdentifier].Data); } }
private void IC_Stroke(object sender, InkCollectorStrokeEventArgs e) { SaveUndoStrokes(); }
private void inkOverlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { _strokes.Add(e.Stroke); _context.BackgroundRecognizeWithAlternates(); if (_inkOverlay.DefaultDrawingAttributes.Color == FirstColor) _inkOverlay.DefaultDrawingAttributes.Color = SecondColor; else _inkOverlay.DefaultDrawingAttributes.Color = FirstColor; }
private void Event_Stroke(object Sender, InkCollectorStrokeEventArgs e) { InkOverlay myInk = (InkOverlay) Sender; if (myInk.Ink.Strokes.Count == 1) { timer1.Start(); } }
/// <summary> /// When a stroke is collected, add it to the InkAnalyzer. /// After a Stroke has been added, it will be analyzed /// the next time BackgroundAnalyze or Analyze is called. /// </summary> private void MyInkOverlayStroke(object sender, InkCollectorStrokeEventArgs e) { analyzer.AddStroke(e.Stroke); }
void InkOverlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { strokesToRecognize.Add(e.Stroke); recoContext.BackgroundRecognizeWithAlternates(); }
void tab_overlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { form.modified = true; }
void overlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { StartTimer(); }
void ic_Stroke(object sender, InkCollectorStrokeEventArgs e) { rct.StopBackgroundRecognition(); rct.Strokes.Add(e.Stroke); rct.CharacterAutoCompletion = RecognizerCharacterAutoCompletionMode.Full; rct.BackgroundRecognizeWithAlternates(0); }
void mInkPicture_Stroke(object sender, InkCollectorStrokeEventArgs e) { Console.WriteLine("mInkPicture_Stroke >>"); this.DialogResult = dlgRes; this.Close(); Console.WriteLine("<< mInkPicture_Stroke"); }
private void inkoverlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { dbg.WriteLine("----- inkoverlay_Stroke -----"); // Ensure we're on the UI thread. dbg.Assert(!this.InvokeRequired); // Check to make sure we're not erasing. if (inkoverlay.EditingMode == InkOverlayEditingMode.Delete) { return; } try // To prevent exceptions from propagating back to ink runtime. { // Hook for tap-to-select feature, in lasso-mode. if (inkoverlay.EditingMode == InkOverlayEditingMode.Select) { TryTapToSelect(e.Stroke); return; } // Analyze stroke geometry. bool closed; Point[] vertices; double tolerance = 500.0; //Heuristic: 500 seems about right. StrokeAnalyzer.AnalyzeClosedness(e.Stroke, tolerance, out closed, out vertices); // Interpret stroke in document-context: first, consider closed strokes. if (closed) { // Check for a small elliptical-gesture over two or more bodies. // If so, it's a pin joint! Rectangle bbox = e.Stroke.GetBoundingBox(); Point midp = Geometry.Midpoint(bbox); RigidBodyBase[] hits = doc.HitTestBodies(midp); if (hits.Length >= 2 && bbox.Width < 1000 && bbox.Height < 1000) { RigidBodyBase top = hits[0]; RigidBodyBase bottom = hits[1]; // Snap to CG if close to either top's or bottom's. if (Geometry.DistanceBetween(midp, top.CG) < 500.0) { midp = top.CG; } else if (Geometry.DistanceBetween(midp, bottom.CG) < 500.0) { midp = bottom.CG; } dbg.WriteLine("new JointMech"); JointMech newmech = new JointMech(); newmech.EndpointA = BodyRef.For(bottom, midp); newmech.EndpointB = BodyRef.For(top, midp); newmech.strokeid = e.Stroke.Id; doc.Mechanisms.Add(newmech); // Repaint area around the newmech (unions with stroke bbox, below). Rectangle dirtybbox = newmech.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); return; } else { // Larger stroke, and/or no centerpoint hits -- form a new solid body. RigidBodyBase newbody = MakeBodyFromClosedStroke(e.Stroke, vertices); // Repaint area around the newbody (unions with stroke bbox, below). Rectangle dirtybbox = newbody.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); // Select it, to show the smart tag. inkoverlay.Selection = this.MakeSingleStrokeCollection(e.Stroke); return; } } // An unclosed stroke -- // Check if head and/or tail is hit on existing bodies. int np = e.Stroke.PacketCount; Point head = e.Stroke.GetPoint(0), tail = e.Stroke.GetPoint(np - 1); RigidBodyBase[] headhits = doc.HitTestBodies(head); RigidBodyBase[] tailhits = doc.HitTestBodies(tail); if (headhits.Length == 0 && tailhits.Length == 0) { // Neither head or tail hit, so let's try harder to make a body // out of this stroke. Point[] dummy; tolerance = 2000.0; //Heuristic: vastly relax closure tolerance. StrokeAnalyzer.AnalyzeClosedness(e.Stroke, tolerance, out closed, out dummy); if (closed) { RigidBodyBase newbody = MakeBodyFromClosedStroke(e.Stroke, vertices); // Repaint area around the newbody (unions with stroke bbox, below). Rectangle dirtybbox = newbody.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); // Select it, to show the smart tag. inkoverlay.Selection = this.MakeSingleStrokeCollection(e.Stroke); return; } else if (Geometry.DistanceBetween(head, tail) > 500.0) { // Interpret this stroke as a gravity-vector. GravitationalForceMech newgrav = new GravitationalForceMech(); newgrav.Body = null; // Applies to all bodies! newgrav.origin = head; newgrav.vector = Vector.FromPoints(head, tail); // Repaint area around the gravity vector (unions with stroke bbox, below). Rectangle dirtybbox = newgrav.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); // Throw out the current gravity-vector stroke, if it exists. if (doc.Gravity != null) { dirtybbox = doc.Gravity.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); Stroke old = GetStrokeById(doc.Gravity.strokeid); doc.Ink.DeleteStroke(old); } newgrav.strokeid = e.Stroke.Id; doc.Gravity = newgrav; return; } else { // This stroke is probably an accidental tap -- discard it. e.Cancel = true; return; } } if (headhits.Length > 0 && tailhits.Length == 0) { // If only the head is hit, it must be an 'attractive force'. RigidBodyBase body = headhits[0]; dbg.WriteLine("new ExternalForceMech"); ExternalForceMech newmech = new ExternalForceMech(); newmech.Body = BodyRef.For(body, head); newmech.vector = Vector.FromPoints(head, tail); newmech.strokeid = e.Stroke.Id; doc.Mechanisms.Add(newmech); // Repaint area around the newmech (unions with stroke bbox, below). Rectangle dirtybbox = newmech.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); return; } if (headhits.Length == 0 && tailhits.Length > 0) { // If only the tail is hit, it must be a 'propulsive force'. RigidBodyBase body = tailhits[0]; dbg.WriteLine("new PropulsiveForceMech"); PropulsiveForceMech newmech = new PropulsiveForceMech(); newmech.Body = BodyRef.For(body, tail); newmech.vector = Vector.FromPoints(head, tail); newmech.strokeid = e.Stroke.Id; doc.Mechanisms.Add(newmech); // Repaint area around the newmech (unions with stroke bbox, below). Rectangle dirtybbox = newmech.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); return; } if (true) // scope { // Create a binding mechanism between two bodies. RigidBodyBase headbody = headhits[0], tailbody = tailhits[0]; // If both the head and the tail hit same object, // attach the head to the one behind. if (Object.ReferenceEquals(headbody, tailbody)) { if (headhits.Length > 1) { headbody = headhits[1]; } else if (tailhits.Length > 1) { tailbody = tailhits[1]; } else { // Don't self-connect. We will perhaps interpret the stroke as an // anchor-gesture or a selection-gesture, // but if we cannot, we will cancel. int nc = e.Stroke.PolylineCusps.Length; if (np <= 25) { inkoverlay.Selection = MakeSingleStrokeCollection(headbody.strokeid); SetEditingMode(InkOverlayEditingMode.Select, false); } else if (np <= 150 && (nc >= 3 && nc <= 5)) { headbody.anchored = !headbody.anchored; //toggle } e.Cancel = true; // Repaint area around the headbody (unions with stroke bbox, below). Rectangle dirtybbox = headbody.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); return; } } // Create a rope, rod, or spring out of the stroke. MechanismBase newmech = MakeRodRopeOrSpring(e.Stroke, headbody, tailbody); if (newmech != null) { // Repaint area around the newmech (unions with stroke bbox, below). Rectangle dirtybbox = newmech.BoundingBox; InvalidateInkSpaceRectangle(dirtybbox); return; } else { // Throw out the stroke, and return. e.Cancel = true; return; } } } catch (Exception ex) { // Cancel the stroke, and log the error. e.Cancel = true; Global.HandleThreadException(this, new System.Threading.ThreadExceptionEventArgs(ex)); } finally { // Repaint the area around the stroke (unions with newbody/mech region, above). Rectangle dirtybbox = e.Stroke.GetBoundingBox(); InvalidateInkSpaceRectangle(dirtybbox); } }
private void inkOverlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { if(this.InvokeRequired) return; //in effect, this is reseting the timer to start from the beginning. edgeTimer.Stop(); edgeTimer.Start(); //Check if the stroke was a tap, and if it was, get the node it tapped. Node n = StrokeManager.TappedNode(e.Stroke,graph); if(n != null) { //If its eraser mode, delete it. if(inkOverlay.EditingMode == InkOverlayEditingMode.Delete) { graph.Remove(n); } else { //Any other mode, select it and change to selection mode int[] ids = {n.Stroke.Id}; selectionButton(sender, e); inkOverlay.Selection = e.Stroke.Ink.CreateStrokes(ids); } e.Stroke.Ink.DeleteStroke(e.Stroke); Invalidate(); return; } //The following code is for pen mode only strokes if(inkOverlay.EditingMode != InkOverlayEditingMode.Ink) return; //If a stroke is inside a node, store it in n n = StrokeManager.HitNodeTest(e.Stroke,graph); //If the stroke is closed and it's a start, assign a home or destination if(StrokeManager.isClosed(e.Stroke) && n != null && StrokeManager.isStar(e.Stroke)) { graph.AssignNode(n); RecognizeWeight(); //Attempt at recognizing weight is made after every stroke. } //If the stroke is closed and it is not enclosed in a node and is a circle, make a circular node else if(StrokeManager.isClosed(e.Stroke) && n==null && e.Stroke.PacketCount > StrokeManager.SMALLEST_N_SIZE && StrokeManager.FitsCircleProperties(e.Stroke)) { Stroke circle = StrokeManager.makeCircle(inkOverlay, e.Stroke); Node circleNode = new Node(circle); graph.Add(circleNode); RecognizeWeight(); } //If the stroke is close and it is not enclosed in a node and is a rectangle, make a rectangular node else if(StrokeManager.isClosed(e.Stroke) && n==null && e.Stroke.PacketCount > StrokeManager.SMALLEST_N_SIZE && StrokeManager.FitsRectProperties(e.Stroke)) { Stroke rect = StrokeManager.makeRect(inkOverlay, e.Stroke); Node rectNode = new Node(rect); graph.Add(rectNode); RecognizeWeight(); } //if the stroke isn't closed, then it is an edge. else if(!StrokeManager.isClosed(e.Stroke)) { //Get all the nodes hit by this stroke and create edges for them Nodes edgeNodes = StrokeManager.ifEdgeGetNodes(e.Stroke, graph); if(edgeNodes != null && !StrokeManager.isScratchOut(e.Stroke)) { for(int i=0; i<edgeNodes.Length()-1; i++) { if(!Edge.hasEdge(edgeNodes[i],edgeNodes[i+1])) { Edge edge = new Edge(edgeNodes[i],edgeNodes[i+1],inkOverlay); graph.Add(edge); } } } else if(StrokeManager.isScratchOut(e.Stroke)) { ArrayList objs = StrokeManager.HitObjects(e.Stroke,graph); for(int i=0; i<objs.Count; i++) { graph.Remove(objs[i]); } } RecognizeWeight(); } else { //if all of the above fails, then the stroke is considered for edge weights Edge hitEdge = StrokeManager.HitEdgeTest(e.Stroke,graph); if(hitEdge != null) { /* if the edge hit is the same as the previous one, * accumulate strokes for it before recognizing, * if it's a different edge, then recognize and add this * stroke to the new edge. */ if(prevEdgeHit == null) prevEdgeHit = hitEdge; if(hitEdge.Equals(prevEdgeHit)) { myRecognizer.Strokes.Add(StrokeManager.CopyStroke(e.Stroke)); } else { RecognizeWeight(); prevEdgeHit = hitEdge; myRecognizer.Strokes.Add(StrokeManager.CopyStroke(e.Stroke)); } } } e.Stroke.Ink.DeleteStroke(e.Stroke); Invalidate(); }
/// <summary> /// Event Handler from Ink Collector's Stroke event /// /// This event is fired when a new lasso stroke is drawn. /// In this case, it is necessary to update the selected /// strokes information. /// </summary> /// <param name="sender">The control that raised the event.</param> /// <param name="e">The event arguments.</param> private void myInkCollector_Stroke(object sender, InkCollectorStrokeEventArgs e ) { // This stroke corresponds to the lasso - // cancel it so that it is not added into the ink e.Cancel = true; Strokes hitStrokes = null; // If there are enough lasso points, perform a hit test // to determine which strokes were selected. if (lassoPoints.Count > 2) { // Convert the lasso points from pixels to ink space Point[] inkLassoPoints = (Point[])lassoPoints.ToArray(typeof(Point)); using (Graphics g = CreateGraphics()) { myInkCollector.Renderer.PixelToInkSpace(g, ref inkLassoPoints); } // Perform a hit test on this ink collector's ink to // determine which points were selected by the lasso stroke. // // Note that there is a slight inefficiency here since the // lasso stroke is part of the ink and, therefore, part of the // hit test - even though we don't need it. It would have // been more efficient to remove the stroke from the ink before // calling HitTest. However, it is not good practice to modify // the stroke inside of its own event handler. hitStrokes = myInkCollector.Ink.HitTest(inkLassoPoints, LassoPercent); hitStrokes.Remove(e.Stroke); } // Reset the lasso points lassoPoints.Clear(); lastDrawnLassoDot = Point.Empty; // Use helper method to set the selection SetSelection(hitStrokes); }
private void inkOverlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { Strokes strokes = null; Ink copiedInk = null; try { // Eraser strokes are transparent, we don't need to send them if (e.Stroke.DrawingAttributes.Transparency != 255) { // Give the stroke an identifier, so we can delete it remotely e.Stroke.ExtendedProperties.Add(StrokeIdentifier, Guid.NewGuid().ToString()); // Copy the stroke into its own Ink object, so that it can be serialized strokes = inkOverlay.Ink.CreateStrokes(new int[]{e.Stroke.Id}); copiedInk = e.Stroke.Ink.ExtractStrokes(strokes, ExtractFlags.CopyFromOriginal); // Send it across the network wb.SendObject(new SerializedInk(copiedInk)); } } catch(Exception ex) { Log(ex.ToString()); } finally { if(strokes != null) { strokes.Dispose(); } if(copiedInk != null) { copiedInk.Dispose(); } } }
void inkOverlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { // throw new NotImplementedException(); }
public void run() { System.Threading.Thread.CurrentThread.Priority = ThreadPriority.Highest; try { bool clientTalking = true; //a loop that reads from and writes to the socket while (clientTalking) { //get what client wants to say... byte[] bytes = new byte[8192]; // 8 KB de dados int bytesRec = this.socket.Receive(bytes); // System.Diagnostics.Debug.WriteLine("----- Recebido... -----"); ArrayList list = (ArrayList)getObjectWithByteArray(bytes); Object o = list[0]; String nomeEvento = (String)list[1]; // EVENTOS DO ARGO if (nomeEvento.Equals("PROT_atualiza_modelo_cliente")) { } if (nomeEvento.Equals("PROT_atualiza_modelo_cliente_inicial")) { ArrayList ListDoc = (ArrayList)o; // Global.main.OpenForCollaboration( ); Global.main.Invoke(new MainForm.DelegateOpenMetod(Global.main.OpenForCollaboration), new object[] { (TextWriter)ListDoc[0] }); } // Recebeu a notificação que algum cliente entrou na da sessão! if (nomeEvento.Equals("PROT_inicio_sessao")) { } // Recebeu a notificação que algum cliente saiu da sessão! if (nomeEvento.Equals("PROT_fim_sessao")) { } // Esta ação foi removida para a experiência /* if (nomeEvento.equals("ActionDeleteFromDiagram-actionPerformed")) * ActionDeleteFromDiagram.SINGLETON.actionPerformedImpl((ActionEvent) o); */ // EVENTOS DO GEF // Desenho do TelePointer! #region mouseMovedPointer if (nomeEvento.Equals("mouseMovedPointer")) { /* * // Sem os telePointers por enquanto * ArrayList dados = (ArrayList) o; * * FigPointer fp = Global.main.fpA; * String Id_tele = (String) dados[2]; * * if (Id_tele.Equals("1") ) fp = Global.main.fpA; * if (Id_tele.Equals("2") ) fp = Global.main.fpB; * if (Id_tele.Equals("3") ) fp = Global.main.fpC; * if (Id_tele.Equals("4") ) fp = Global.main.fpD; * * fp.setCor((Color) dados[1] ); * fp.setNome((String) dados[3]); * * fp.setLocation((Point) dados[0]); */ } #endregion #region inkoverlay_Stroke if (nomeEvento.Equals("inkoverlay_Stroke")) { ArrayList dados = (ArrayList)o; Ink x = new Ink(); x.Load((byte[])dados[0]); Stroke s = x.Strokes[x.Strokes.Count - 1]; // Testes: Adicionando a coleção de strokes! Global.main.doc.Ink.CreateStroke(s.GetPoints()); InkCollectorStrokeEventArgs e = new InkCollectorStrokeEventArgs(null, s, false); // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateToMethod(Global.main.inkoverlay_StrokeImpl), new object[] { e }); } #endregion #region inkoverlay_StrokesDeleting if (nomeEvento.Equals("inkoverlay_StrokesDeleting")) { ArrayList dados = (ArrayList)o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.inkoverlay_StrokesDeletingImpl), new object[] { dados }); } #endregion #region inkoverlay_SelectionMovedOrResized if (nomeEvento.Equals("inkoverlay_SelectionMovedOrResized")) { ArrayList dados = (ArrayList)o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.inkoverlay_SelectionMovedOrResizedImpl), new object[] { dados }); } #endregion #region hover_EditCloneClicked if (nomeEvento.Equals("hover_EditCloneClicked")) { ArrayList dados = (ArrayList)o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.hover_EditCloneClickedImpl), new object[] { dados }); } #endregion #region hover_EditStraightenClicked if (nomeEvento.Equals("hover_EditStraightenClicked")) { ArrayList dados = (ArrayList)o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.hover_EditStraightenClickedImpl), new object[] { dados }); } #endregion #region hover_EditPropertiesClicked if (nomeEvento.Equals("hover_EditPropertiesClicked")) { ArrayList dados = (ArrayList)o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateEraseMethod(Global.main.hover_EditPropertiesClickedImpl), new object[] { dados }); } #endregion // Controles da simulação remota #region hover_AnimateClicked_Start if (nomeEvento.Equals("Start")) { // É preciso criar outra Thread aqui para continuar recebendo os dados.... // E depois é preciso terminá-la cr = new ClienteRecebe(this.socket); ThreadStart threadDelegate = new ThreadStart(cr.run); Thread tClienteRecebe = new Thread(threadDelegate); tClienteRecebe.Start(); Object dados = (Object)o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedStartImpl), new object[] { dados }); /* tClienteRecebe.Abort(); * Thread.Sleep(5); * cr = null; */ } #endregion #region hover_AnimateClicked_Stop if (nomeEvento.Equals("Stop")) { Object dados = (Object)o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedStopImpl), new object[] { dados }); // System.Threading.Thread.CurrentThread.Abort(); // É preciso cometer suicídio, ou seja, essa Thread deve se auto-terminar if (cr != null) { return; } } #endregion #region hover_AnimateClicked_Pause if (nomeEvento.Equals("Pause")) { Object dados = (Object)o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedPauseImpl), new object[] { dados }); } #endregion #region hover_AnimateClicked_Resume if (nomeEvento.Equals("Resume")) { Object dados = (Object)o; // Precisa utilizar delegates, pois existem problemas quando uma Thread que não é // o formulário atualiza a interface gráfica Global.main.Invoke(new MainForm.DelegateSimulationMetod(Global.main.hover_AnimateClickedResumeImpl), new object[] { dados }); } #endregion } } catch (ThreadAbortException e) { MessageBox.Show("ThreadAbortException in ClienteRecebe:" + e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } catch (Exception e) { MessageBox.Show("Exception in ClienteRecebe:" + e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private void inkCollector_Stroke(object sender, InkCollectorStrokeEventArgs e) { if (dryInk != null) { dryInk.Wait(); } dryInk = Task.Run(() => { Matrix originalMatrix = new Matrix(); inkCollector.Renderer.GetViewTransform(ref originalMatrix); Strokes strokesToDry = inkCollector.Ink.Strokes; Point p = viewportLocation; using (Matrix m = new Matrix()) { using (Graphics g = CreateGraphics()) { inkCollector.Renderer.PixelToInkSpace(g, ref p); g.Dispose(); } m.Translate(p.X, p.Y); inkCollector.Renderer.SetViewTransform(m); } LinkedList <ManagedBitmap> mapsToDry = new LinkedList <ManagedBitmap>(); foreach (Stroke s in strokesToDry) { for (int pi = 0; pi < s.GetPoints().Length; pi++) { Point sp2 = s.GetPoint(pi); using (Graphics g = CreateGraphics()) { inkCollector.Renderer.InkSpaceToPixel(g, ref sp2); } ManagedBitmap mbmp; if (!managedMaps.ContainsKey(new Point(getGridX(sp2.X), getGridY(sp2.Y)))) { mbmp = new ManagedBitmap(getGridX(sp2.X) * mapsWidth, getGridY(sp2.Y) * mapsHeight, new Bitmap(mapsWidth, mapsHeight)); mbmp.g.DrawRectangle(Pens.LightGray, 0, 0, mapsWidth - 1, mapsHeight - 1); mbmp.g.DrawString("(" + getGridX(sp2.X) + ", " + getGridY(sp2.Y) + ")", this.Font, Brushes.Black, 10f, 10f); managedMaps.Add(new Point(getGridX(sp2.X), getGridY(sp2.Y)), mbmp); } else { mbmp = managedMaps[new Point(getGridX(sp2.X), getGridY(sp2.Y))]; } if (!mapsToDry.Contains(mbmp)) { mapsToDry.AddLast(mbmp); } } } foreach (ManagedBitmap mbmp in mapsToDry) { //Point gridLocation = managedMaps.FirstOrDefault(x => x.Value == mbmp).Key; //System.Diagnostics.Debug.WriteLine(gridLocation.ToString()); Point mbmpP1 = new Point(mbmp.x + viewportLocation.X, mbmp.y + viewportLocation.Y); using (Graphics g = CreateGraphics()) { inkCollector.Renderer.PixelToInkSpace(g, ref mbmpP1); } Matrix m, m2; m = m2 = new Matrix(); inkCollector.Renderer.GetViewTransform(ref m); inkCollector.Renderer.GetViewTransform(ref m2); m.Translate(-mbmpP1.X, -mbmpP1.Y); inkCollector.Renderer.SetViewTransform(m); inkCollector.Renderer.Draw(mbmp.map, strokesToDry); inkCollector.Renderer.SetViewTransform(m2); this.drawingArea.CreateGraphics().DrawImage(mbmp.map, mbmp.x - viewportLocation.X, mbmp.y - viewportLocation.Y); mbmp.map.MakeTransparent(this.drawingArea.BackColor); } inkCollector.Renderer.SetViewTransform(originalMatrix); e.Cancel = true; if (strokesToDry.Count != 0) { inkCollector.Ink.DeleteStrokes(strokesToDry); } return(0); }); }
private void inkOverlay_Stroke(object sender, InkCollectorStrokeEventArgs e) { if (this.InvokeRequired) { return; } //in effect, this is reseting the timer to start from the beginning. edgeTimer.Stop(); edgeTimer.Start(); //Check if the stroke was a tap, and if it was, get the node it tapped. Node n = StrokeManager.TappedNode(e.Stroke, graph); if (n != null) { //If its eraser mode, delete it. if (inkOverlay.EditingMode == InkOverlayEditingMode.Delete) { graph.Remove(n); } else { //Any other mode, select it and change to selection mode int[] ids = { n.Stroke.Id }; selectionButton(sender, e); inkOverlay.Selection = e.Stroke.Ink.CreateStrokes(ids); } e.Stroke.Ink.DeleteStroke(e.Stroke); Invalidate(); return; } //The following code is for pen mode only strokes if (inkOverlay.EditingMode != InkOverlayEditingMode.Ink) { return; } //If a stroke is inside a node, store it in n n = StrokeManager.HitNodeTest(e.Stroke, graph); //If the stroke is closed and it's a start, assign a home or destination if (StrokeManager.isClosed(e.Stroke) && n != null && StrokeManager.isStar(e.Stroke)) { graph.AssignNode(n); RecognizeWeight(); //Attempt at recognizing weight is made after every stroke. } //If the stroke is closed and it is not enclosed in a node and is a circle, make a circular node else if (StrokeManager.isClosed(e.Stroke) && n == null && e.Stroke.PacketCount > StrokeManager.SMALLEST_N_SIZE && StrokeManager.FitsCircleProperties(e.Stroke)) { Stroke circle = StrokeManager.makeCircle(inkOverlay, e.Stroke); Node circleNode = new Node(circle); graph.Add(circleNode); RecognizeWeight(); } //If the stroke is close and it is not enclosed in a node and is a rectangle, make a rectangular node else if (StrokeManager.isClosed(e.Stroke) && n == null && e.Stroke.PacketCount > StrokeManager.SMALLEST_N_SIZE && StrokeManager.FitsRectProperties(e.Stroke)) { Stroke rect = StrokeManager.makeRect(inkOverlay, e.Stroke); Node rectNode = new Node(rect); graph.Add(rectNode); RecognizeWeight(); } //if the stroke isn't closed, then it is an edge. else if (!StrokeManager.isClosed(e.Stroke)) { //Get all the nodes hit by this stroke and create edges for them Nodes edgeNodes = StrokeManager.ifEdgeGetNodes(e.Stroke, graph); if (edgeNodes != null && !StrokeManager.isScratchOut(e.Stroke)) { for (int i = 0; i < edgeNodes.Length() - 1; i++) { if (!Edge.hasEdge(edgeNodes[i], edgeNodes[i + 1])) { Edge edge = new Edge(edgeNodes[i], edgeNodes[i + 1], inkOverlay); graph.Add(edge); } } } else if (StrokeManager.isScratchOut(e.Stroke)) { ArrayList objs = StrokeManager.HitObjects(e.Stroke, graph); for (int i = 0; i < objs.Count; i++) { graph.Remove(objs[i]); } } RecognizeWeight(); } else { //if all of the above fails, then the stroke is considered for edge weights Edge hitEdge = StrokeManager.HitEdgeTest(e.Stroke, graph); if (hitEdge != null) { /* if the edge hit is the same as the previous one, * accumulate strokes for it before recognizing, * if it's a different edge, then recognize and add this * stroke to the new edge. */ if (prevEdgeHit == null) { prevEdgeHit = hitEdge; } if (hitEdge.Equals(prevEdgeHit)) { myRecognizer.Strokes.Add(StrokeManager.CopyStroke(e.Stroke)); } else { RecognizeWeight(); prevEdgeHit = hitEdge; myRecognizer.Strokes.Add(StrokeManager.CopyStroke(e.Stroke)); } } } e.Stroke.Ink.DeleteStroke(e.Stroke); Invalidate(); }
/// <summary> /// Event Handler from Ink Overlay's Stroke event /// This event is fired when a new stroke is drawn. /// In this case, it is necessary to update the ink divider's /// strokes collection. The event is fired even when the eraser stroke is created. /// The event handler must filter out the eraser strokes. /// </summary> /// <param name="sender">The control that raised the event.</param> /// <param name="e">The event arguments.</param> private void myInkOverlay_Stroke(object sender, InkCollectorStrokeEventArgs e ) { // Filter out the eraser stroke. if(InkOverlayEditingMode.Ink == myInkOverlay.EditingMode) { // Add the new stroke to the ink divider's strokes collection myInkDivider.Strokes.Add(e.Stroke); if(miAutomaticLayoutAnalysis.Checked) { // Call DivideInk DivideInk(); // Repaint the screen to reflect the change DrawArea.Refresh(); } } }
void mInkPicture_Stroke(object sender, InkCollectorStrokeEventArgs e) { mFormPalette.OnInkDrawMode(); }