Search Results

Search found 47 results on 2 pages for 'raiseevent'.

Page 1/2 | 1 2  | Next Page >

  • Is there any performance overhead in using RaiseEvent in .net

    - by Sachin
    Is there any performance overhead in using RaiseEvent in .net I have a code which is similar to following. Dim _startTick As Integer = Environment.TickCount 'Do some Task' Dim duration As Integer = Environment.TickCount - _startTick Logger.Debug("Time taken : {0}", duration) RaiseEvent Datareceived() Above code returns Time Taken :1200 Time Taken :1400 But if remove RaiseEvent it returns Time Taken :110 Time Taken :121 I am surprised that the raiseevent is called after the logging of time taken. How it effects total time taken. I am working on Compact framework. Update: In the Eventhandler I had given a MsgBox. When I removed the message box it is now showing time taken as 110,121,etc i.e. less that 500 milliseconds. If I put the Msgbox back in eventhandler it shows 1200,1400,etc i.e. more that a second. More surprised now.(Event is raised after the logging part)

    Read the article

  • Firing MouseLeftButtonDown event programmatically

    - by RajenK
    Hi, I'm trying to manually fire a MouseLeftButtonDown event on a WPF control programmatically, as I am using the Microsoft Surface SDK, which does not fire MouseLeftButtonDown events, but ContactDown events. Basically I'm trying to push the MouseLeftButtonDown event down to the control, to fire off the correct behavior on the control, while handling a ContactDown event. I'm guessing I have to somehow use the RaiseEvent method on the control to do this with MouseButtonEventArgs, but I'm having some trouble figuring out the parameters. Thanks in advance for your help!

    Read the article

  • .NET Programmatically invoke screenclick doesn't work?

    - by ropstah
    I'm trying to programmatically invoke an onclick event however the click is not received/handled. Am I missing something, or is security preventing the click to be executed? I have a forms application which is invisible. Basically I would like to say: DoDoubleClick(wait, x, y) This should raise two click (mousedown+mouseup) events on screen with the specified wait interval. However the click isn't received in a Flash application in Firefox (which is running at that moment). Here's my code: Form: Public Class Form1 Private WithEvents gmh As GlobalMouseHook Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load gmh = New GlobalMouseHook() Me.Visible = false gmh.DoDoubleClick(50, 800, 600) End Sub Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed gmh.Dispose() End Sub Private Sub gmh_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gmh.MouseDown End Sub Private Sub gmh_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gmh.MouseMove End Sub Private Sub gmh_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gmh.MouseUp End Sub End Class GlobalMouseHook class: Friend Class GlobalMouseHook Implements IDisposable Private hhk As IntPtr = IntPtr.Zero Private disposedValue As Boolean = False Public Event MouseDown As MouseEventHandler Public Event MouseUp As MouseEventHandler Public Event MouseMove As MouseEventHandler Public Sub New() Hook() End Sub Private Sub Hook() Dim hInstance As IntPtr = LoadLibrary("User32") hhk = SetWindowsHookEx(WH_MOUSE_LL, AddressOf Me.HookProc, hInstance, 0) End Sub Private Sub Unhook() UnhookWindowsHookEx(hhk) End Sub Public Sub DoDoubleClick(ByVal wait As Integer, ByVal x As Integer, ByVal y As Integer) RaiseEvent MouseDown(Me, New MouseEventArgs(MouseButtons.Left, 1, x, y, 0)) RaiseEvent MouseUp(Me, Nothing) System.Threading.Thread.Sleep(wait) RaiseEvent MouseDown(Me, New MouseEventArgs(MouseButtons.Left, 1, x, y, 0)) RaiseEvent MouseUp(Me, Nothing) End Sub Private Function HookProc(ByVal nCode As Integer, ByVal wParam As UInteger, ByRef lParam As MSLLHOOKSTRUCT) As Integer If nCode >= 0 Then Select Case wParam Case WM_LBUTTONDOWN RaiseEvent MouseDown(Me, New MouseEventArgs(MouseButtons.Left, 0, lParam.pt.x, lParam.pt.y, 0)) Case WM_RBUTTONDOWN RaiseEvent MouseDown(Me, New MouseEventArgs(MouseButtons.Right, 0, lParam.pt.x, lParam.pt.y, 0)) Case WM_MBUTTONDOWN RaiseEvent MouseDown(Me, New MouseEventArgs(MouseButtons.Middle, 0, lParam.pt.x, lParam.pt.y, 0)) Case WM_LBUTTONUP, WM_RBUTTONUP, WM_MBUTTONUP RaiseEvent MouseUp(Nothing, Nothing) Case WM_MOUSEMOVE RaiseEvent MouseMove(Nothing, Nothing) Case WM_MOUSEWHEEL, WM_MOUSEHWHEEL Case Else Console.WriteLine(wParam) End Select End If Return CallNextHookEx(hhk, nCode, wParam, lParam) End Function Private Structure API_POINT Public x As Integer Public y As Integer End Structure Private Structure MSLLHOOKSTRUCT Public pt As API_POINT Public mouseData As UInteger Public flags As UInteger Public time As UInteger Public dwExtraInfo As IntPtr End Structure Private Const WM_MOUSEWHEEL As UInteger = &H20A Private Const WM_MOUSEHWHEEL As UInteger = &H20E Private Const WM_MOUSEMOVE As UInteger = &H200 Private Const WM_LBUTTONDOWN As UInteger = &H201 Private Const WM_LBUTTONUP As UInteger = &H202 Private Const WM_MBUTTONDOWN As UInteger = &H207 Private Const WM_MBUTTONUP As UInteger = &H208 Private Const WM_RBUTTONDOWN As UInteger = &H204 Private Const WM_RBUTTONUP As UInteger = &H205 Private Const WH_MOUSE_LL As Integer = 14 Private Delegate Function LowLevelMouseHookProc(ByVal nCode As Integer, ByVal wParam As UInteger, ByRef lParam As MSLLHOOKSTRUCT) As Integer Private Declare Auto Function LoadLibrary Lib "kernel32" (ByVal lpFileName As String) As IntPtr Private Declare Auto Function SetWindowsHookEx Lib "user32.dll" (ByVal idHook As Integer, ByVal lpfn As LowLevelMouseHookProc, ByVal hInstance As IntPtr, ByVal dwThreadId As UInteger) As IntPtr Private Declare Function CallNextHookEx Lib "user32" (ByVal hhk As IntPtr, ByVal nCode As Integer, ByVal wParam As UInteger, ByRef lParam As MSLLHOOKSTRUCT) As Integer Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hhk As IntPtr) As Boolean ' IDisposable Protected Overridable Sub Dispose(ByVal disposing As Boolean) If Not Me.disposedValue Then If disposing Then ' TODO: free other state (managed objects). End If Unhook() End If Me.disposedValue = True End Sub ' This code added by Visual Basic to correctly implement the disposablepattern. Public Sub Dispose() Implements IDisposable.Dispose ' Do not change this code. Put cleanup code in Dispose(ByValdisposing As Boolean) above. Dispose(True) GC.SuppressFinalize(Me) End Sub End Class

    Read the article

  • Inheritance, commands and event sourcing

    - by Arthis
    In order not to redo things several times I wanted to factorize common stuff. For Instance, let's say we have a cow and a horse. The cow produces milk, the horse runs fast, but both eat grass. public class Herbivorous { public void EatGrass(int quantity) { var evt= Build.GrassEaten .WithQuantity(quantity); RaiseEvent(evt); } } public class Horse : Herbivorous { public void RunFast() { var evt= Build.FastRun; RaiseEvent(evt); } } public class Cow: Herbivorous { public void ProduceMilk() { var evt= Build.MilkProduced; RaiseEvent(evt); } } To eat Grass, the command handler should be : public class EatGrassHandler : CommandHandler<EatGrass> { public override CommandValidation Execute(EatGrass cmd) { Contract.Requires<ArgumentNullException>(cmd != null); var herbivorous= EventRepository.GetById<Herbivorous>(cmd.Id); if (herbivorous.IsNull()) throw new AggregateRootInstanceNotFoundException(); herbivorous.EatGrass(cmd.Quantity); EventRepository.Save(herbivorous, cmd.CommitId); } } so far so good. I get a Herbivorous object , I have access to its EatGrass function, whether it is a horse or a cow doesn't matter really. The only problem is here : EventRepository.GetById<Herbivorous>(cmd.Id) Indeed, let's imagine we have a cow that has produced milk during the morning and now wants to eat grass. The EventRepository contains an event MilkProduced, and then come the command EatGrass. With the CommandHandler, we are no longer in the presence of a cow and the herbivorious doesn't know anything about producing milk . what should it do? Ignore the event and continue , thus allowing the inheritance and "general" commands? or throw an exception to forbid execution, it would mean only CowEatGrass, and HorseEatGrass might exists as commands ? Thanks for your help, I am just beginning with these kinds of problem, and I would be glad to have some news from someone more experienced.

    Read the article

  • Custom Event - invokation list implementation considerations

    - by M.A. Hanin
    I'm looking for some pointers on implementing Custom Events in VB.NET (Visual Studio 2008, .NET 3.5). I know that "regular" (non-custom) Events are actually Delegates, so I was thinking of using Delegates when implementing a Custom Event. On the other hand, Andrew Troelsen's "Pro VB 2008 and the .NET 3.5 Platform" book uses Collection types in all his Custom Events examples, and Microsoft's sample codes match that line of thought. So my question is: what considerations should I have when choosing one design over the other? What are the pros and cons for each design? Which of these resembles the inner-implementation of "regular" events? Below is a sample code demonstrating the two designs. Public Class SomeClass Private _SomeEventListeners As EventHandler Public Custom Event SomeEvent As EventHandler AddHandler(ByVal value As EventHandler) _SomeEventListeners = [Delegate].Combine(_SomeEventListeners, value) End AddHandler RemoveHandler(ByVal value As EventHandler) _SomeEventListeners = [Delegate].Remove(_SomeEventListeners, value) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) _SomeEventListeners.Invoke(sender, e) End RaiseEvent End Event Private _OtherEventListeners As New List(Of EventHandler) Public Custom Event OtherEvent As EventHandler AddHandler(ByVal value As EventHandler) _OtherEventListeners.Add(value) End AddHandler RemoveHandler(ByVal value As EventHandler) _OtherEventListeners.Remove(value) End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As System.EventArgs) For Each handler In _OtherEventListeners handler(sender, e) Next End RaiseEvent End Event End Class

    Read the article

  • deserialize system.outofmemoryexception

    - by clanier9
    I've got a serializeable class called Cereal with several public fields shown here <Serializable> Public Class Cereal Public id As Integer Public cardType As Type Public attacker As String Public defender As String Public placedOn As String Public attack As Boolean Public placed As Boolean Public played As Boolean Public text As String Public Sub New() End Sub End Class My client computer is sending a new Cereal to the host by serializing it shown here 'sends data to host stream (c1) Private Sub cSendText(ByVal Data As String) Dim bf As New BinaryFormatter Dim c As New Cereal c.text = Data bf.Serialize(mobjClient.GetStream, c) End Sub The host listens to the stream for activity and when something gets put on it, it is supposed to deserialize it to a new Cereal shown here 'accepts data sent from the client, raised when data on host stream (c2) Private Sub DoReceive(ByVal ar As IAsyncResult) Dim intCount As Integer Try 'find how many byte is data SyncLock mobjClient.GetStream intCount = mobjClient.GetStream.EndRead(ar) End SyncLock 'if none, we are disconnected If intCount < 1 Then RaiseEvent Disconnected(Me) Exit Sub End If Dim bf As New BinaryFormatter Dim c As New Cereal c = CType(bf.Deserialize(mobjClient.GetStream), Cereal) If c.text.Length > 0 Then RaiseEvent LineReceived(Me, c.text) Else RaiseEvent CardReceived(Me, c) End If 'starts listening for action on stream again SyncLock mobjClient.GetStream mobjClient.GetStream.BeginRead(arData, 0, 1024, AddressOf DoReceive, Nothing) End SyncLock Catch e As Exception RaiseEvent Disconnected(Me) End Try End Sub when the following line executes, I get a System.OutOfMemoryException and I cannot figure out why this isn't working. c = CType(bf.Deserialize(mobjClient.GetStream), Cereal) The stream is a TCPClient stream. I'm new to serialization/deserialization and using visual studio 11

    Read the article

  • Raising C# events with an extension method - is it bad?

    - by Kyralessa
    We're all familiar with the horror that is C# event declaration. To ensure thread-safety, the standard is to write something like this: public event EventHandler SomethingHappened; protected virtual void OnSomethingHappened(EventArgs e) { var handler = SomethingHappened; if (handler != null) handler(this, e); } Recently in some other question on this board (which I can't find now), someone pointed out that extension methods could be used nicely in this scenario. Here's one way to do it: static public class EventExtensions { static public void RaiseEvent(this EventHandler @event, object sender, EventArgs e) { var handler = @event; if (handler != null) handler(sender, e); } static public void RaiseEvent<T>(this EventHandler<T> @event, object sender, T e) where T : EventArgs { var handler = @event; if (handler != null) handler(sender, e); } } With these extension methods in place, all you need to declare and raise an event is something like this: public event EventHandler SomethingHappened; void SomeMethod() { this.SomethingHappened.RaiseEvent(this, EventArgs.Empty); } My question: Is this a good idea? Are we missing anything by not having the standard On method? (One thing I notice is that it doesn't work with events that have explicit add/remove code.)

    Read the article

  • WinForms Web Browser control forcing refocus?

    - by Corey Ogburn
    I'm trying to automate a web process where I need to click a button repeatedly. When my code "clicks" that button (an HtmlElement obtained from the WebBrowser control I have on my form) then it brings focus back to my application, more specifically the WebBrowser control. I wish to better automate this process so that the user can do other things while the process is going on, but that can't happen if the window is unminimizing itself because it's attaining focus. The code associated with the clicking is: HtmlElement button = Recruiter.Document.GetElementById("recruit_link"); button.InvokeMember("click"); I've also tried button.RaiseEvent("onclick") and am getting the exact same results, with focus problems and all. I've also tried hiding the form, but when the InvokeMember/RaiseEvent method is called, whatever I was working on loses focus but since the form is not visible then the focus seems to go nowhere. The only non-default thing about the webbrowser is it's URI being set to my page and ScriptErrorsSuppressed being set to True.

    Read the article

  • Boiler plate code replacement - is there anything bad about this code?

    - by Benjol
    I've recently created these two (unrelated) methods to replace lots of boiler-plate code in my winforms application. As far as I can tell, they work ok, but I need some reassurance/advice on whether there are some problems I might be missing. (from memory) static class SafeInvoker { //Utility to avoid boiler-plate InvokeRequired code //Usage: SafeInvoker.Invoke(myCtrl, () => myCtrl.Enabled = false); public static void Invoke(Control ctrl, Action cmd) { if (ctrl.InvokeRequired) ctrl.BeginInvoke(new MethodInvoker(cmd)); else cmd(); } //Replaces OnMyEventRaised boiler-plate code //Usage: SafeInvoker.RaiseEvent(this, MyEventRaised) public static void RaiseEvent(object sender, EventHandler evnt) { var handler = evnt; if (handler != null) handler(sender, EventArgs.Empty); } } EDIT: See related question here UPDATE Following on from deadlock problems (related in this question), I have switched from Invoke to BeginInvoke (see an explanation here). Another Update Regarding the second snippet, I am increasingly inclined to use the 'empty delegate' pattern, which fixes this problem 'at source' by declaring the event directly with an empty handler, like so: event EventHandler MyEventRaised = delegate {};

    Read the article

  • BackgroundWorker RunWorkerCompleted in a Component

    - by Sphynx
    I'm familiar with the following: "If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of System.ComponentModel.RunWorkerCompletedEventArgs. If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised." However, I've encountered a weird glitch. In my component, there's an instance of BackgroundWorker. Even though it's not running in the debugger, the exception remains unhandled by the worker. Even simplified code produces an unhandled exception (and RunWorkerCompleted doesn't fire): Throw New ArgumentException("Test") The main thing is the code of RunWorkerComplete: RaiseEvent UpdateComplete(Me, New AsyncCompletedEventArgs(e.Error, e.Cancelled, e.Result)) I need the component to expose the worker exception through a public event. If I remove the RaiseEvent call, the exception becomes handled by the worker, and accessible through e.Error. Apparently, raising an event causes the worker to miss the exception. How can that be?

    Read the article

  • redirect an event in VB.NET

    - by serhio
    I havea a UserControl1 (in witch I have an Label1) in Form1. I want to catch the MouseDown event from label and send it like from UserControl I do: Public Class UserControl1 Shadows Custom Event MouseDown As MouseEventHandler AddHandler(ByVal value As MouseEventHandler) AddHandler Label1.MouseDown, value End AddHandler RemoveHandler(ByVal value As MouseEventHandler) RemoveHandler Label1.MouseDown, value End RemoveHandler RaiseEvent(ByVal sender As Object, ByVal e As MouseEventArgs) 'RaiseMouseEvent(Me, e) ??? ' End RaiseEvent End Event End Class However, when I set in the Form1 the UserControl Private Sub UserControl11_MouseDown(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles UserControl11.MouseDown MessageBox.Show(sender.GetType.Name) 'here I have 'Label', want 'UserControl' End Sub

    Read the article

  • Application Module Extension in Oracle Application R12

    - by Manoj Madhusoodanan
    In this blog I will describe how to Extend Application Module.I will explain this based on my previous blog PL/SQL based EO.  I want to extend FndUserAM to add a procedure to raise a custom business event when the FND_USER has created successfully. Here I am using a custom business event "xxcust.oracle.apps.demo_event". Please find the code used in Business Event. TablePackage Following steps needs to perform. 1) Download all files pertaining to "Entity Object Based on PL/SQL" to JDEV_USER_HOME/myprojects and JDEV_USER_HOME/myclasses.If you want to see the content of source java file decompile it and save it in JDEV_USER_HOME/myprojects. 2) Create XXFndUserAM as follows. 3) Add following method to XXFndUserAMImpl.    import oracle.apps.fnd.framework.OAException;   import oracle.apps.fnd.framework.server.OADBTransactionImpl;   import oracle.apps.fnd.wf.bes.BusinessEvent;   import oracle.apps.fnd.wf.bes.BusinessEventException;    import java.sql.Connection;     public void raiseEvent(String userName) {        String eventName = "xxcust.oracle.apps.demo_event";        String eventKey = userName;        Connection conn = ((OADBTransactionImpl)getOADBTransaction()).getJdbcConnection();         BusinessEvent event = null;         try{             event = new BusinessEvent(eventName, eventKey);             /* Setting Parameters */             event.setStringProperty("USER_NAME",userName);             event.setStringProperty("STATUS","User has created sucessfully");             event.raise(conn);             }             catch (BusinessEventException e) {                 throw new OAException("Exception occured when invoking web service - "+e.getMessage());             }             getOADBTransaction().commit();    } 4) Create a controller which extends from xxcust.oracle.apps.fnd.user.webui.CreateFndUserCO.Call raiseEvent method from new controller. 5) Create substitution for FndUserAM. 6) Migrate following files to $JAVA_TOP. xxcustom.oracle.apps.fnd.user.server.FndUserAMImpl.javaxxcustom.oracle.apps.fnd.user.server.XXFndUserAM.xmlxxcustom.oracle.apps.fnd.user.webui.XXCreateFndUserCO.java 8) Migrate the substitution. 9) Restart the server. 10) Personalize the page /xxcust/oracle/apps/fnd/user/webuiCreateFndUserPG and set the new controller. 11) Verify the substitution has properly applied by clicking About the Page. 12) Access the page and create a user. You can the the result of the Business Event.

    Read the article

  • Raising event in custom control.

    - by SeSSiZ
    Hi all, I'm writing a custom textblock control thats populate hyperlinks and raises event when clicked to hyperlink. I wrote this code but I got stucked. My code is : Imports System.Text.RegularExpressions Public Class CustomTextBlock Inherits TextBlock Public Event Klik As EventHandler(Of EventArgs) Public ReadOnly InlineCollectionProperty As DependencyProperty = DependencyProperty.Register("InlineCollection", GetType(String), GetType(CustomTextBlock), New PropertyMetadata(New PropertyChangedCallback(AddressOf CustomTextBlock.InlineChanged))) Private Shared Sub InlineChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs) DirectCast(sender, CustomTextBlock).Inlines.Clear() Dim kelimeler = Split(e.NewValue, " ") For i = 0 To kelimeler.Length - 1 If Regex.Match(kelimeler(i), "(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?").Success Then Dim x = New Hyperlink(New Run(kelimeler(i))) x.AddHandler(Hyperlink.ClickEvent, New RoutedEventHandler(AddressOf t_Click)) x.ToolTip = kelimeler(i) x.Tag = kelimeler(i) DirectCast(sender, CustomTextBlock).Inlines.Add(x) If Not i = kelimeler.Length Then DirectCast(sender, CustomTextBlock).Inlines.Add(" ") Else DirectCast(sender, CustomTextBlock).Inlines.Add(kelimeler(i)) If Not i = kelimeler.Length Then DirectCast(sender, CustomTextBlock).Inlines.Add(" ") End If ''//Console.WriteLine(kelime(i).ToString.StartsWith("@")) Next kelimeler = Nothing End Sub Public Property InlineCollection As String Get Return DirectCast(GetValue(InlineCollectionProperty), String) End Get Set(ByVal value As String) SetValue(InlineCollectionProperty, value) End Set End Property Private Shared Sub t_Click(ByVal sender As Hyperlink, ByVal e As System.Windows.RoutedEventArgs) e.Handled = True RaiseEvent Klik(sender, EventArgs.Empty) End Sub End Class This code gives error at RaiseEvent Klik(sender, EventArgs.Empty) Error is : Cannot refer to an instance member of a class from within a shared method or shared member initializer without an expliticit instance of the class. Thanks for your answers, Alper

    Read the article

  • Are there any shortcuts/easier(VB) style way for raising events in C#?

    - by Eric
    Example in VB I have a worker class Public Class worker Public Event EventNumber1(ByVal messages As Dictionary(Of Integer, String)) Public Event EventNumber2(ByVal message As String) Public Sub CallEventNumber1() Dim dict As New Dictionary(Of Integer, String) dict.Add(1, "EventNumber1 First message") dict.Add(2, "EventNumber1 Second message") RaiseEvent EventNumber1(dict) End Sub Public Sub CallEventNumber2() RaiseEvent EventNumber2("I am an EventNumber2 Message") End Sub End Class and wire them up in another class with AddHandler _worker.EventNumber1, AddressOf EventNumber1Handler AddHandler _worker.EventNumber2, AddressOf EventNumber2Handler and in C# the worker class class Worker { public delegate void EventNumber1Handler(Dictionary<int, string> messages); public delegate void EventNumber2Handler(string message); public event EventNumber1Handler EventNumber1; public event EventNumber2Handler EventNumber2; public void CallEventNumber1() { Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "EventNumber1 First message"); dict.Add(2, "EventNumber1 Second message"); if (EventNumber1 != null) EventNumber1(dict); } public void CallEventNumber2() { if (EventNumber2 != null) EventNumber2("I am an EventNumber2 Message"); } } and wire that up with worker.EventNumber1 += new Worker.EventNumber1Handler(worker_EventNumber1); worker.EventNumber2 += new Worker.EventNumber2Handler(worker_EventNumber2); So I guess my question is do I always need to add the delegate along with the event in c#? Is there any new syntax for c# 3.0/4.0? Regards _Eric

    Read the article

  • Change user control appearance based on state

    - by John
    I have a user control that consists of four overlapping items: 2 rectangles, an ellipse and a lable <UserControl x:Class="UserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="50.1" Height="45.424" Background="Transparent" FontSize="24"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="3.303*" /> <RowDefinition Height="40*" /> <RowDefinition Height="2.121*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="5.344*" /> <ColumnDefinition Width="40.075*" /> <ColumnDefinition Width="4.663*" /> </Grid.ColumnDefinitions> <Rectangle Name="Rectangle1" RadiusX="5" RadiusY="5" Fill="DarkGray" Grid.ColumnSpan="3" Grid.RowSpan="3" /> <Ellipse Name="ellipse1" Fill="{Binding State}" Margin="0.016,0.001,4.663,0" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Stroke="Black" IsEnabled="True" Panel.ZIndex="2" /> <Label Name="lblNumber" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Foreground="White" FontWeight="Bold" FontSize="24" Grid.Column="1" Grid.Row="1" Padding="0" Panel.ZIndex="3">9</Label> <Rectangle Grid.Column="1" Grid.Row="1" Margin="0.091,0,4.663,0" Fill="Blue" Name="rectangle2" Stroke="Black" Grid.ColumnSpan="2" Panel.ZIndex="1" /> </Grid> Here is my business object that I want to control the state of my user control: Imports System.Data Imports System.ComponentModel Public Class BusinessObject Implements INotifyPropertyChanged 'Public logger As log4net.ILog Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged Private _state As States Public Enum States State1 State2 State3 End Enum Public Property State() As States Get Return _state End Get Set(ByVal value As States) If (value <> _state) Then _state = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("State")) End If End Set End Property Protected Sub OnPropertyChanged(ByVal name As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name)) End Sub I want to be able to change the state of a business object in the code behind and have that change the colors of multiple shapes in my usercontrol. I'm not sure about how to do the binding. I set the datacontext of the user control in the code behind but not sure if that's right. I'm new to WPF and programming in general and I'm stuck on where to go from here. Any recommendations would be greatly appreciated!!

    Read the article

  • ReSharper C# Live Template for Declaring Routed Event

    - by Bart Read
    Here's another WPF ReSharper Live Template for you. This one is for declaring standalone routed events of any type. Again, it's pretty simple:        #region $EVENTNAME$ Routed Event       public static readonly RoutedEvent $EVENTNAME$Event = EventManager.RegisterRoutedEvent(            "$EVENTNAME$",           RoutingStrategy.$ROUTINGSTRATEGY$,           typeof( $EVENTHANDLERDELEGATE$ ),           typeof( $DECLARINGTYPE$ ) );       public event $EVENTHANDLERDELEGATE$ $EVENTNAME$       {           add { AddHandler( $EVENTNAME$Event, value ); }           remove { RemoveHandler( $EVENTNAME$Event, value ); }       }       protected virtual void On$EVENTNAME$()       {           RaiseEvent( new $EVENTARGSTYPE$( $EVENTNAME$Event, this ) );           $END$       }       #endregion Here are my previous posts along the same lines: ReSharper C# Live Template for Read-Only Dependency Property and Routed Event Boilerplate ReSharper C# Live Template for Dependency Property and Property Change Routed Event Boilerplate Code Enjoy! Technorati Tags: resharper,live template,c#,routed event,wpf,boilerplate,code generation

    Read the article

  • WPF Lookless Control Events

    - by Scott
    I have the following class: public class LooklessControl : Control { public List<int> IntList { get; private set; } public int CurrentInt { get; private set; } private int _index = 0; static LooklessControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(LooklessControl), new FrameworkPropertyMetadata(typeof(LooklessControl))); } public LooklessControl() { IntList = new List<int>(); for (int i = 0; i < 10; i++) { IntList.Add(i); } CurrentInt = IntList[_index]; } public static readonly RoutedCommand NextItemCommand = new RoutedCommand("NextItemCommand", typeof(LooklessControl)); private void ExecutedNextItemCommand(object sender, ExecutedRoutedEventArgs e) { NextItemHandler(); } private void CanExecuteNextItemCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } public static readonly RoutedCommand PrevItemCommand = new RoutedCommand("PrevItemCommand", typeof(LooklessControl)); private void ExecutedPrevItemCommand(ExecutedRoutedEventArgs e) { PrevItemHandler(); } private void CanExecutePrevItemCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } public static readonly RoutedEvent NextItemEvent = EventManager.RegisterRoutedEvent("NextItemEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(LooklessControl)); public event RoutedEventHandler NextItem { add { AddHandler(NextItemEvent, value); } remove { RemoveHandler(NextItemEvent, value); } } private void RaiseNextItemEvent() { RoutedEventArgs args = new RoutedEventArgs(LooklessControl.NextItemEvent); RaiseEvent(args); } public static readonly RoutedEvent PrevItemEvent = EventManager.RegisterRoutedEvent("PrevItemEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(LooklessControl)); public event RoutedEventHandler PrevItem { add { AddHandler(PrevItemEvent, value); } remove { RemoveHandler(PrevItemEvent, value); } } private void RaisePrevItemEvent() { RoutedEventArgs args = new RoutedEventArgs(LooklessControl.PrevItemEvent); RaiseEvent(args); } private void NextItemHandler() { _index++; if (_index == IntList.Count) { _index = 0; } CurrentInt = IntList[_index]; RaiseNextItemEvent(); } private void PrevItemHandler() { _index--; if (_index == 0) { _index = IntList.Count - 1; } CurrentInt = IntList[_index]; RaisePrevItemEvent(); } } The class has a default style, in Generic.xaml, that looks like this: <Style x:Key="{x:Type local:LooklessControl}" TargetType="{x:Type local:LooklessControl}"> <Setter Property="Height" Value="200"/> <Setter Property="Width" Value="90"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type local:LooklessControl}"> <Border BorderBrush="Black" BorderThickness="1" Padding="2"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="20"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Rectangle Grid.Row="0" Fill="LightGray"/> <Rectangle Grid.Row="1" Fill="Gainsboro"/> <Grid Grid.Row="0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="10"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="10"/> </Grid.ColumnDefinitions> <Path Grid.Column="0" x:Name="pathLeftArrow" Data="M0,0.5 L1,1 1,0Z" Width="6" Height="14" Stretch="Fill" HorizontalAlignment="Center" Fill="SlateBlue"/> <TextBlock Grid.Column="1" Name="textBlock" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=CurrentInt}" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Junction" FontSize="13"/> <Path Grid.Column="2" x:Name="pathRightArrow" Data="M0,0 L1,0.5 0,1Z" Width="6" Height="14" Stretch="Fill" HorizontalAlignment="Center" Fill="SlateBlue"/> </Grid> <ListBox Grid.Row="1" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Background="Transparent" ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IntList}"/> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> How do I make it so that when the user clicks on pathLeftArrow it fires LooklessControl.PrevItemCommand, or or they click on pathRightArrow and it fires LooklessControl.NextItemCommand, or they click on an item in the ListBox and LooklessControl is notified of the newly selected item? In other words, without adding x:Class to the top of Generic.xaml and thus creating a code-behind file for it, which I assume you wouldn't want to do, how do you handle events for elements in your xaml that don't have a Command property (which is just about everything other than a Button)? Should LooklessControl have it's own XAML file (much like what you get when you create a new UserControl) associated with it that Generic.xaml just pulls in as a MergedDictionar as its default template? Or is there some other acknowledged way to do what I'm trying to do?

    Read the article

  • Handling events exposed on a .NET class via COM in VB6

    - by PeanutPower
    Handling events exposed on a .NET class via COM in VB6 My test .NET (class libary registered for interop in compiler settings) code: Imports System.Runtime.InteropServices <InterfaceType(ComInterfaceType.InterfaceIsIDispatch), ComVisible(True)> _ Public Interface MyEventInterface <DispId(1)> Event Exploded(ByVal Text As String) <DispId(2)> Sub PushRedButton() End Interface <ClassInterface(ClassInterfaceType.None)> _ Public Class EventTest Implements MyEventInterface Public Event Exploded(ByVal Text As String) Implements MyEventInterface.Exploded Public Sub PushRedButton() Implements MyEventInterface.PushRedButton RaiseEvent Exploded("Bang") End Sub End Class My test VB6 application winforms code (which references the above class libary): Public ct As New ComTest1.EventTest Private Sub Command1_Click() ct.add_Exploded (ExplodedHandler) ct.PushRedButton ct.remove_Exploded (ExplodedHandler) End Sub Private Sub ExplodedHandler(ByVal Text As String) MsgBox Text End Sub Specifially I'm not sure how to set up the handler in VB6 the compile error I get is "Argument not optional" on this line in the VB6: ct.add_Exploded (ExplodedHandler)

    Read the article

  • Is there a way to know in VB.NET if a handler has been registered for an event?

    - by Seth Spearman
    In C# I can test for this... public event EventHandler Trigger; protected void OnTrigger(EventArgs e) { if (Trigger != null) Trigger(this, e); } Is there a way to do this in VB.NET? Test for null I mean? MORE INFO I forgot to mention. I have classes written in C# but I am writing my unit tests in VB.NET. I am trying this in the unit test... If myObject.Trigger IsNot Nothing Then 'do something End If This is causing a compile time error which says ... "Public Event Trigger is an Event and cannot be called directly. Use the RaiseEvent statement to raise an event." Seth

    Read the article

  • Events raised by BackgroundWorker not executed on expected thread

    - by Topdown
    A winforms dialog is using BackgroundWorker to perform some asynchronous operations with significant success. On occasion, the async process being run by the background worker will need to raise events to the winforms app for user response (a message that asks the user if they wish to cancel), the response of which captured in an CancelEventArgs type of the event. Being an implementation of threading, I would have expected the RaiseEvent of the worker to fire, and then the worker would continue, hence requiring me to pause the worker until the response is received. Instead however, the worker is held to wait for the code executed by the raise event to complete. It seems like method I am calling via the event call is actually on the worker thread used by the background worker, and I am surprised, since I expected to see it on the Main Thread which is where the mainform is running. Also surprisingly, there are no cross thread exceptions thrown. Can somebody please explain why this is not as I expect?

    Read the article

  • What's the VB.NET equivalent of this C# code for wiring up and declaring an event?

    - by Ben McCormack
    I'm working on a tutorial to build a media player in Silverlight and am trying to wire up an EventHandler to the timer.Tick event of a DispatchTimer object so that the time of the video is synced with a Slider object. The sample code is in C# and I can't for the life of me figure out the proper syntax in VB.NET with RaiseEvent and/or Handles to wire up the event. Below is the relevant C# code. I'll include comments on where I'm getting stuck. private DispatchTimer timer; public Page() { //... timer = new DispatchTimer(); timer.Interval = TimeSpan.FromMilliseconds(50); timer.Tick += new EventHandler(timer_Tick); // <== I get stuck here b/c // I can't do "timer.Tick += ..." in VB.NET } void timer_Tick(object sender, EventArgs e) { if (VideoElement.NaturalDuration.TimeSpan.TotalSeconds > 0) { sliderScrubber.Value = VideoElement.Position.TotalSeconds / VideoElement.NaturalDuration.TimeSpan.TotalSeconds; } }

    Read the article

  • How to make Event visible?

    - by eflles
    Inside a Silverlight library project I have a public event, which is not visible for other classes. How can I make the event visible? When I try the following code, I can not locate the event in the "ReceivingClass". .dll - file: Public Class MyClass Public Event MyEvent(ByVal sender As Object, ByVal e As EventArgs) Public Sub OnStart() RaiseEvent MyEvent(Me, new EventArgs) End Sub End Class Silverlight app: Imports MyClass Public Class ReceivingClass Public Sub New() Dim myClass As new MyClass AddHandler myClass.MyEvent, AddressOf Me.EventHandler End Sub Private Sub EventHandler(ByVal sender As Object, ByVal e As EventArgs) 'Handle Event End Sub End Class

    Read the article

  • WithEvents LinkedList is it Impossible?

    - by serhio
    What is the optimal approach to a WithEvents Collection - VB.NET? Have you any remarks on the code bellow (skipping the Nothing verifications)? The problem is when I obtain the LinkedListNode(Of Foo) in a For Each block I can set myNode.Value = something, and here is a handlers leak... -Could I override the FooCollection's GetEnumerator in this case? -No. :( cause NotInheritable Class LinkedListNode(Of T) Class Foo Public Event SelectedChanged As EventHandler End Class Class FooCollection Inherits LinkedList(Of Foo) Public Event SelectedChanged As EventHandler Protected Overloads Sub AddFirst(ByVal item As Foo) AddHandler item.SelectedChanged, AddressOf OnSelectedChanged MyBase.AddFirst(item) End Sub Protected Overloads Sub AddLast(ByVal item As Foo) AddHandler item.SelectedChanged, AddressOf OnSelectedChanged MyBase.AddLast(item) End Sub ' ------------------- ' Protected Overloads Sub RemoveFirst() RemoveHandler MyBase.First.Value.SelectedChanged, _ AddressOf OnSelectedChanged MyBase.RemoveFirst() End Sub Protected Overloads Sub RemoveLast(ByVal item As Foo) RemoveHandler MyBase.Last.Value.SelectedChanged, _ AddressOf OnSelectedChanged MyBase.RemoveLast() End Sub ' ------------------- ' Protected Sub OnSelectedChanged(ByVal sender As Object, ByVal e As EventArgs) RaiseEvent SelectedChanged(sender, e) End Sub End Class

    Read the article

  • How to raise CComponent event in Yii

    - by srigi
    Let's assume I have Component (say Graph like Yahoo Finance) rendered on the page. Component view template contains bunch of a_hrefs which I wanto to switch period in graph. I created Event and Event handler in Component. I have two questions: How to raise event on Graph Component via those a_hrefs (should they be part of Graph?)? How to redraw Graph without loosing curent page context (section, filter - specified as $_GET values)? My Graph Component look like this: Yii::import('zii.widgets.CPortlet'); class Graph extends CPortlet { private $_period; /* ********************** * * COMPONENT PROPERTIES * * ********************** */ public function getPeriod() { return $this-_period; } public function setPeriod($period) { $this-_period = $period; } /* ********************** * * GENERIC * * ********************** */ public function init() { parent::init(); // assign event handlers $this-onPeriodChange = array($this, 'handlePeriodChange'); } protected function renderContent() { $this-render('graph'); } /* ********************** * * EVENTS * * ********************** */ public function onPeriodChange($event) { $this-raiseEvent('onPeriodChange', $event); } /* ********************** * * EVENT HANDLERS * * ********************** */ public function handlePeriodChange($event) { // CODE } }

    Read the article

  • Convert an interface's event from VB.Net to C#

    - by Jules
    Hi, I'm struggling to convert the below code to C#. Class Class1 Implements IMyInterface Public Event MyEvent(ByVal sender As Object, ByVal e As MyEventArgs) Implements IMyInterface.MyEvent Public Sub New() AddHandler Me.Slider.ValueChanged, AddressOf OnSliderValueChanged End Sub Private Sub OnSliderValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) RaiseEvent MyEvent(Me, New MyEventArgs()) End Sub End Class Here's what visual studio inserts when I ask it to implement for me: event EventHandler<MyEventArgs> IMyInterface.MyEvent { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } With a bit of googling I'm sure I can find out what to replace the NotImplementedException parts with but VS is still telling me that the definition is not implemented anyway.

    Read the article

1 2  | Next Page >