Search Results

Search found 4334 results on 174 pages for 'sender'.

Page 24/174 | < Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >

  • Why thread in background is not waiting for task to complete?

    - by Haris Hasan
    I am playing with async await feature of C#. Things work as expected when I use it with UI thread. But when I use it in a non-UI thread it doesn't work as expected. Consider the code below private void Click_Button(object sender, RoutedEventArgs e) { var bg = new BackgroundWorker(); bg.DoWork += BgDoWork; bg.RunWorkerCompleted += BgOnRunWorkerCompleted; bg.RunWorkerAsync(); } private void BgOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { } private async void BgDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { await Method(); } private static async Task Method() { for (int i = int.MinValue; i < int.MaxValue; i++) { var http = new HttpClient(); var tsk = await http.GetAsync("http://www.ebay.com"); } } When I execute this code, background thread don't wait for long running task in Method to complete. Instead it instantly executes the BgOnRunWorkerCompleted after calling Method. Why is that so? What am I missing here? P.S: I am not interested in alternate ways or correct ways of doing this. I want to know what is actually happening behind the scene in this case? Why is it not waiting?

    Read the article

  • how to do display text message from cellphone to textbox

    - by Jiggy Degamo
    I am just making a project automated polling system using sms but i just a beginner of serial communication i have seen a code on the net so i apply it as my guide just a simple text message and display it on the textbox it connects but the provlem is its didn't display on the textbox. here is the code below please help me why it didn't display and please give me a cite that have a tutorial of serial communication using vb.net Imports System.IO.Ports Public Class Form1 Dim inputData As String = "" Private WithEvents serialPort1 As New IO.Ports.SerialPort Public Event DataReceived As IO.Ports.SerialDataReceivedEventHandler Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed ' Close the Serial Port serialPort1.Close() End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'Set values for some properties serialPort1.PortName = "COM10" serialPort1.BaudRate = 2400 SerialPort1.Parity = IO.Ports.Parity.None SerialPort1.DataBits = 8 SerialPort1.StopBits = IO.Ports.StopBits.One SerialPort1.Handshake = IO.Ports.Handshake.None SerialPort1.RtsEnable = True ' Open the Serial Port SerialPort1.Open() 'Writes data to the Serial Port output buffer If SerialPort1.IsOpen = True Then SerialPort1.Write("MicroCommand") End If End Sub ' Receive data from the Serial Port 'Show received data on UI controls and do something Public Sub DoUpdate() TextBox1.Text = TextBox1.Text & inputData End Sub Private Sub serialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serialPort1.DataReceived inputData = serialPort1.ReadExisting 'or serialPort1.ReadLine Me.Invoke(New EventHandler(AddressOf DoUpdate)) End Sub End Class

    Read the article

  • Read specific line from text file, according to Checked Listbox selection number.

    - by Manolis
    Heya, i want to create an application which will read a specific line from a text file and show it in a textbox. The line will be chosen according to the number of the listbox selection i will make. Here's the code: Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim i As Integer For i = 0 To Me.CheckedListBox1.CheckedIndices.Count - 1 Me.CheckedListBox1.SetItemChecked(Me.CheckedListBox1.CheckedIndices(0),False) Next i End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click If CheckedListBox1.CheckedItems.Count <> 0 Then Dim reader As New System.IO.StreamReader(CurDir() & "\" & "READ.txt") Dim x As Integer Dim s As String = "" For x = 0 To CheckedListBox1.CheckedItems.Count - 1 s = s & "Answer " & (x + 1).ToString & ") " & CheckedListBox1.CheckedItems(x).ToString & ControlChars.CrLf & reader.ReadLine() & ControlChars.CrLf & ControlChars.CrLf Next x Answer.Text = (s) Else MessageBox.Show("Please select questions.", "Error", _ MessageBoxButtons.OK, _ MessageBoxIcon.Information) Return End If End Sub End Class So lets say i 'check' the first, second, and fifth items from the checked listbox, i want it to read from the text file the first, second, and fifth lines of text and show them in the textbox. The current code just reads line 1, 2, 3 (...) in order, no matter what item i have 'checked'. Thanks in advance!

    Read the article

  • Implementation of delegates in C#

    - by Ram
    Hi, I am trying to learn on how to use delegates efficiently in C# and I was just wondering if anyone can guide me through... The following is a sample implementation using delegates... All I am doing is just passing a value through a delegate from one class to another... Please tell me if this is the right way to implement... And also your suggestions... Also, please note that I have de-registered the delegate in : void FrmSample_FormClosing(object sender, FormClosingEventArgs e) { sampleObj.AssignValue -= new Sample.AssignValueDelegate(AssignValue); } Is this de-registration necessary? The following is the code that I have written.. public partial class FrmSample : Form { Sample sampleObj; public FrmSample() { InitializeComponent(); this.Load += new EventHandler(FrmSample_Load); this.FormClosing += new FormClosingEventHandler(FrmSample_FormClosing); sampleObj = new Sample(); sampleObj.AssignValue = new Sample.AssignValueDelegate(AssignValue); } void FrmSample_FormClosing(object sender, FormClosingEventArgs e) { sampleObj.AssignValue -= new Sample.AssignValueDelegate(AssignValue); } void FrmSample_Load(object sender, EventArgs e) { sampleObj.LoadValue(); } void AssignValue(string value) { MessageBox.Show(value); } } class Sample { public delegate void AssignValueDelegate(string value); public AssignValueDelegate AssignValue; internal void LoadValue() { if (AssignValue != null) { AssignValue("This is a test message"); } } } Pls provide your feedback on whether this is right... Thanks, Ram

    Read the article

  • Why isn't the Cache invalidated after table update using the SqlCacheDependency?

    - by Jason
    I have been trying to get SqlCacheDependency working. I think I have everything set up correctly, but when I update the table, the item in the Cache isn't invalidated. Can you look at my code and see if I am missing anything? I enabled the Service Broker for the Sandbox database. I have placed the following code in the Global.asax file. I also restart IIS to make sure it is called. void Application_Start(object sender, EventArgs e) { SqlDependency.Start(ConfigurationManager.ConnectionStrings["SandboxConnectionString"].ConnectionString); } I have placed this entry in the web.config file: <system.web> <caching> <sqlCacheDependency enabled="true" pollTime="10000"> <databases> <add name="Sandbox" connectionStringName="SandboxConnectionString"/> </databases> </sqlCacheDependency> </caching> </system.web> I call this code to put the item into the cache: protected void CacheDataSetButton_Click(object sender, EventArgs e) { using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SandboxConnectionString"].ConnectionString)) { using (SqlCommand sqlCommand = new SqlCommand("SELECT PetID, Name, Breed, Age, Sex, Fixed, Microchipped FROM dbo.Pets", sqlConnection)) { using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand)) { DataSet petsDataSet = new DataSet(); sqlDataAdapter.Fill(petsDataSet, "Pets"); SqlCacheDependency petsSqlCacheDependency = new SqlCacheDependency(sqlCommand); Cache.Insert("Pets", petsDataSet, petsSqlCacheDependency, DateTime.Now.AddSeconds(10), Cache.NoSlidingExpiration); } } } } Then I bind the GridView with this code: protected void BindGridViewButton_Click(object sender, EventArgs e) { if (Cache["Pets"] != null) { GridView1.DataSource = Cache["Pets"] as DataSet; GridView1.DataBind(); } } Between attempts to DataBind the GridView, I change the table's values expecting it to invalidate the Cache["Pets"] item, but it seems to stay in the Cache indefinitely.

    Read the article

  • Why am I getting "Message sent to deallocated instance" in Objective-C?

    - by Dave C
    I have several buttons on my app that are being created dynamically. They are all pointed at the button click event when pressed. When the button pressed method is called, the sender's tag (int value) is parsed into the controller's house ID. It works with one of the buttons — the first one created, to be specific — but the others throw the following error: -[CFNumber intValue]: message sent to deallocated instance 0xc4bb0ff0 I am not releasing these buttons anywhere in my code. I haven't set them to autorelease or anything like that. I'm just wondering why they are doing this on the click. The button click event: - (IBAction) ButtonClick: (id) sender { HouseholdViewController *controller = [[HouseholdViewController alloc] initWithNibName:@"HouseholdViewController" bundle:nil]; controller.delegate = self; controller.HouseID = [(NSInteger)[(UIButton *)sender tag] intValue]; //this line throws an error controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; [self presentModalViewController:controller animated:YES]; [controller release]; } Where I am creating the buttons: UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(MyLongInScreenCoords, MyLatInScreenCoords, 50, 50); UIImage *buttonImageNormal = [UIImage imageNamed:@"blue_pin.png"]; UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:50 topCapHeight:50]; [button setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal]; [self.view addSubview:button]; button.tag = [NSNumber numberWithInt:[[words objectAtIndex: i] intValue]]; ButtonPoints[CurrentHouseCount][0] = button; ButtonPoints[CurrentHouseCount][1] = [NSValue valueWithCGPoint:CGPointMake(MyActualLat, MyActualLong)]; [button addTarget:self action:@selector(ButtonClick:) forControlEvents:UIControlEventTouchUpInside]; CurrentHouseCount++;

    Read the article

  • How to play simultaneous multiply audio sources in Silverlight

    - by Shurup
    I want to play simultaneous multiply audio sources in Silverlight. So I've created a prototype in Silverlight 4 that should play a two mp3 files containing the same ticks sound with an intervall 1 second. So these files must be sounded as one sound if they will be played together with any whole second offsets (0 and 1, 0 and 2, 1 and 1 seconds, etc.) I my prototype I use two MediaElement (me and me2) objects. DateTime startTime; private void Play_Clicked(object sender, RoutedEventArgs e) { me.SetSource(new FileStream(file1), FileMode.Open))); me2.SetSource(new FileStream(file2), FileMode.Open))); var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1) }; timer.Tick += RefreshData; timer.Start(); } First file should be played at 00:00 sec. and the second in 00:02 second. void RefreshData(object sender, EventArgs e) { if(me.CurrentState != MediaElementState.Playing) { startTime = DateTime.Now; me.Play(); return; } var elapsed = DateTime.Now - startTime; if(me2.CurrentState != MediaElementState.Playing && elapsed >= TimeSpan.FromSeconds(2)) { me2.Play(); ((DispatcherTimer)sender).Stop(); } } The tracks played every time different and not simultaneous as they should (as one sound).

    Read the article

  • How can I make the WebBrowser control navigate to a specific webpage?

    - by tee
    How can I make the code when run the code it go to samsung.com private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { webBrowser1.Navigate("www.samsung.com"); } Please correct it when run program it go to samsung.com using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using mshtml; namespace webhiglight { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) { webBrowser1.Navigate("www.samsung.com"); } private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (webBrowser1.Document != null) { IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2; if (document != null) { IHTMLSelectionObject currentSelection = document.selection; IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange; if (range != null) { const String search = "ant"; if (range.findText(search, search.Length, 2)) { range.select(); } } } } } } }

    Read the article

  • Thread Locking CollectionViewSource

    - by Robert
    I added an event handler to my code and it broke all access to the CollectionViewSources in the SystemHTA class saying "The calling thread cannot access this object because a different thread owns it". My class was working when "this.systemHTA = new SystemHTA();" was placed outside of the DeviceManager_StateChanged() function. public partial class MainWindow : Window { private DeviceManager DeviceManager = DeviceManager.Instance; public SystemHTA systemHTA; public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { DeviceManager.StateChanged += new EventHandler<DeviceManagerStateChangedEventArgs>(DeviceManager_StateChanged); DeviceManager.Initialize(); } void DeviceManager_StateChanged(object sender, DeviceManagerStateChangedEventArgs e) { if (e.State == DeviceManagerState.Operational) { this.systemHTA = new SystemHTA(); } } private void button1_Click(object sender, RoutedEventArgs e) { this.systemHTA.GetViewSourceTest(); } } public class SystemHTA { private CollectionViewSource _deviceTestSource; public SystemHTA() { _deviceTestSource = new CollectionViewSource(); _deviceTestSource.Source = CreateLoadData<HWController>.ControllerCollection; } public void GetViewSourceTest() { ListCollectionView view = (ListCollectionView)_deviceTestSource.View; //This creates an error saying a thread already owns _deviceTestSource } }

    Read the article

  • problem with drag and drop for the winform using c#

    - by karthik
    I dont have the title bar in my winform, so i need to code drag and drop for the entire form. I am using the below code to do it, which works fine. I have two panels in my form, PanelA and PanelB. During the startup i show PanelA where the drag and drop works perfectly. Later when the user clicks the button in PannelA, i need to make PanelA visible false and show the PanelB My drag and drop is not working when the PanelB is loaded in form. Whats the problem here ? private void SerialPortScanner_MouseUp(object sender, MouseEventArgs e) { this.drag = false; } private void SerialPortScanner_MouseDown(object sender, MouseEventArgs e) { this.drag = true; this.start_point = new Point(e.X, e.Y); } private void SerialPortScanner_MouseMove(object sender, MouseEventArgs e) { if (this.drag) { Point p1 = new Point(e.X, e.Y); Point p2 = this.PointToScreen(p1); Point p3 = new Point(p2.X - this.start_point.X, p2.Y - this.start_point.Y); this.Location = p3; } }

    Read the article

  • ScaleTransform transforms non-linearly

    - by Chris
    I am using scale transform to allow a user to resize a control. What happens though is that when you start to move the mouse the control jumps to a new size, and then scales oddly. The further you move your mouse from the starting location the larger the increase in size becomes. I expect its the way I calculate the scale to be applied. Here is the code: private void ResizeGrip_MouseDown(object sender, MouseButtonEventArgs e) { ResizeHandle.CaptureMouse(); //Get the initial coordinate cursor location on the window initBtmX = e.GetPosition(this).X; bottomResize = true; } private void ResizeGrip_MouseUp(object sender, MouseButtonEventArgs e) { bottomResize = false; ResizeHandle.ReleaseMouseCapture(); } private void ResizeGrip_MouseMove(object sender, MouseEventArgs e) { if( bottomResize == true) { //Get the new Y coordinate cursor location double newBtmX = e.GetPosition(this).X; //Get the smallest change between the initial and new cursor location double diffX = initBtmX - newBtmX; // Let our rectangle capture the mouse ResizeHandle.CaptureMouse(); double newWidth = e.GetPosition(this).X - diffX; double scaler = newWidth / ResizeContainer.ActualWidth; Console.WriteLine("newWidth: {0}, scalar: {1}", newWidth, scaler); if (scaler < 0.75 || scaler > 3) return; ScaleTransform scale = new ScaleTransform(scaler, scaler); ResizeContainer.LayoutTransform = scale; } }

    Read the article

  • PyQt - QLabel inheriting

    - by Ockonal
    Hello, i wanna inherit QLabel to add there click event processing. I'm trying this code: class NewLabel(QtGui.QLabel): def __init__(self, parent): QtGui.QLabel.__init__(self, parent) def clickEvent(self, event): print 'Label clicked!' But after clicking I have no line 'Label clicked!' EDIT: Okay, now I'm using not 'clickEvent' but 'mousePressEvent'. And I still have a question. How can i know what exactly label was clicked? For example, i have 2 edit box and 2 labels. Labels content are pixmaps. So there aren't any text in labels, so i can't discern difference between labels. How can i do that? EDIT2: I made this code: class NewLabel(QtGui.QLabel): def __init__(self, firstLabel): QtGui.QLabel.__init__(self, firstLabel) def mousePressEvent(self, event): print 'Clicked' #myLabel = self.sender() # None =) self.emit(QtCore.SIGNAL('clicked()'), "Label pressed") In another class: self.FirstLang = NewLabel(Form) QtCore.QObject.connect(self.FirstLang, QtCore.SIGNAL('clicked()'), self.labelPressed) Slot in the same class: def labelPressed(self): print 'in labelPressed' print self.sender() But there isn't sender object in self. What i did wrong?

    Read the article

  • How do I wait for a C# event to be raised?

    - by Evan Barkley
    I have a Sender class that sends a Message on a IChannel: public class MessageEventArgs : EventArgs { public Message Message { get; private set; } public MessageEventArgs(Message m) { Message = m; } } public interface IChannel { public event EventHandler<MessageEventArgs> MessageReceived; void Send(Message m); } public class Sender { public const int MaxWaitInMs = 5000; private IChannel _c = ...; public Message Send(Message m) { _c.Send(m); // wait for MaxWaitInMs to get an event from _c.MessageReceived // return the message or null if no message was received in response } } When we send messages, the IChannel sometimes gives a response depending on what kind of Message was sent by raising the MessageReceived event. The event arguments contain the message of interest. I want Sender.Send() method to wait for a short time to see if this event is raised. If so, I'll return its MessageEventArgs.Message property. If not, I return a null Message. How can I wait in this way? I'd prefer not to have do the threading legwork with ManualResetEvents and such, so sticking to regular events would be optimal for me.

    Read the article

  • Dynamcally resising an open Accordion

    - by alavers
    I have an Accordion and the height of its content can be dynamically resized. I would like to see the Accordion dynamically respond to the child item's height, but I'm having trouble doing this. <lt:Accordion Name="MyAccordion" SelectionMode="ZeroOrOne" HorizontalAlignment="Stretch"> <lt:AccordionItem Name="MyAccordionItem" Header="MyAccordion" IsSelected="True" HorizontalContentAlignment="Stretch" VerticalAlignment="Stretch"> <StackPanel> <Button Content="Grow" Click="Grow"/> <Button Content="Shrink" Click="Shrink"/> <TextBox Name="GrowTextBox" Text="GrowTextBox" Height="400" Background="Green" SizeChanged="GrowTextBox_SizeChanged"/> </StackPanel> </lt:AccordionItem> </lt:Accordion> private void Grow(object sender, System.Windows.RoutedEventArgs e) { GrowTextBox.Height += 100; } private void Shrink(object sender, System.Windows.RoutedEventArgs e) { GrowTextBox.Height -= 100; } private void GrowTextBox_SizeChanged(object sender, System.Windows.SizeChangedEventArgs e) { MyAccordion.UpdateLayout(); MyAccordionItem.UpdateLayout(); } Mind you, if I collapse and then re-open the accordion, it takes shape just the way I want, but I'd like this resizing to occur immediately when the child resizes. I feebly attempted to fix this by adding a SizeChanged event handler that calls UpdateLayout() on the Accordion and AccordionItem, but this doesn't have any visual effect. I can't figure out where proper resizing takes place inside the Accordion control. Does anyone have an idea?

    Read the article

  • Issue with dynamically loading a user control on button click

    - by Kumar
    I have a page in which I am loading a user control dynamically as follows: Default.aspx: <cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </cc1:ToolkitScriptManager> <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> Default.aspx.cs: protected void Page_Load(object sender, EventArgs e) { var ctrl = LoadControl("~/UserCtrl1.ascx"); ctrl.ID = "ucUserCtrl1"; PlaceHolder1.Controls.Add(ctrl); } Below is the code for UserCtrl1.ascx <asp:Label ID="Label1" runat="server"></asp:Label> <asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Click" /> <br /> <asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder> I am dynamically loading another user control when the Button1 is clicked UserCtrl1.ascx.cs protected void Button1_Click(object sender, EventArgs e) { Label1.Text = "UserControl - 1 button clicked!"; var ctrl = LoadControl("~/UserCtrl2.ascx"); ctrl.ID = "ucUserCtrl2"; PlaceHolder2.Controls.Add(ctrl); } Below is the markup for UserCtrl2.ascx <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Label ID="Label2" runat="server"></asp:Label> <asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click" /> </ContentTemplate> </asp:UpdatePanel> UserCtrl2.ascx.cs protected void Button2_Click(object sender, EventArgs e) { Label2.Text = "UserControl - 2 button clicked!"; } After the page loads when I click the Button1 in UserCtrl1 the click event fires and I am able to see the Label1 text. It also properly loads the UserCtrl2, but when I click the Button2 in UserCtrl2 the click event dosent fire and even worse when I click the Button2 twice the UserCtrl2 control dissappears from the page. How can I fix this?

    Read the article

  • Dynamically cast a control type in runtime

    - by JayT
    Hello, I have an application whereby I dynamically create controls on a form from a database. This works well, but my problem is the following: private Type activeControlType; private void addControl(ContainerControl inputControl, string ControlName, string Namespace, string ControlDisplayText, DataRow drow, string cntrlName) { Assembly assem; Type myType = Type.GetType(ControlName + ", " + Namespace); assem = Assembly.GetAssembly(myType); Type controlType = assem.GetType(ControlName); object obj = Activator.CreateInstance(controlType); Control tb = (Control)obj; tb.Click += new EventHandler(Cntrl_Click); inputControl.Controls.Add(tb); activeControlType = controlType; } private void Cntrl_Click(object sender, EventArgs e) { string test = ((activeControlType)sender).Text; //Problem ??? } How do I dynamically cast the sender object to a class that I can reference the property fields of it. I have googled, and found myself trying everything I have come across..... Now I am extremely confused... and in need of some help Thnx JT

    Read the article

  • Is it good choice to move a Sublayer around a view using UIPanGestureRecognizer?

    - by Pranjal Bikash Das
    I have a CALayer and as sublayer to this CALayer i have added an imageLayer which contains an image of resolution 276x183. I added a UIPanGestureRecognizer to the main view and calculation the coordinates of the CALayer as follows: - (void)panned:(UIPanGestureRecognizer *)sender{ subLayer.frame=CGRectMake([sender locationInView:self.view].x-138, [sender locationInView:self.view].y-92, 276, 183); } in viedDidLoad i have: subLayer.backgroundColor=[UIColor whiteColor].CGColor; subLayer.frame=CGRectMake(22, 33, 276, 183); imageLayer.contents=(id)[UIImage imageNamed:@"A.jpg"].CGImage; imageLayer.frame=subLayer.bounds; imageLayer.masksToBounds=YES; imageLayer.cornerRadius=15.0; subLayer.shadowColor=[UIColor blackColor].CGColor; subLayer.cornerRadius=15.0; subLayer.shadowOpacity=0.8; subLayer.shadowOffset=CGSizeMake(0, 3); [subLayer addSublayer:imageLayer]; [self.view.layer addSublayer:subLayer]; It is giving desired output but a bit slow in the simulator. I have not yet tested it in Device. so my question is - Is it OK to move a CALayer containing an image??

    Read the article

  • Problem with moving a winform using C#

    - by karthik
    My form doesn't have a title bar, so I am implementing the code to drag the entire form around the screen. I am using the below code to do it, which works fine. I have two panels in my form, PanelA and PanelB. During the startup I show PanelA where the dragging works perfectly. Later when the user clicks the button in PanelA, I need to make PanelA invisible and show PanelB However, the dragging does not work when PanelB is shown. What's the problem here? private void SerialPortScanner_MouseUp(object sender, MouseEventArgs e) { this.drag = false; } private void SerialPortScanner_MouseDown(object sender, MouseEventArgs e) { this.drag = true; this.start_point = new Point(e.X, e.Y); } private void SerialPortScanner_MouseMove(object sender, MouseEventArgs e) { if (this.drag) { Point p1 = new Point(e.X, e.Y); Point p2 = this.PointToScreen(p1); Point p3 = new Point(p2.X - this.start_point.X, p2.Y - this.start_point.Y); this.Location = p3; } }

    Read the article

  • Controlling the alpha of a UIImageView with Slider ..Can' t get it

    - by user1824839
    first i' d like to say this Forum was really helpfull for me that just started coding some weeks ago .. I succeed to do a quite nice app for the moment , than, but i m stuck on this : HOW COULD I CONTROL THE ALPHA OF A UIIMAGEVIEW , WITH A SLIDER EMBEDED IN ANOTHER VIEW ??? ; Basically i' like to do like the alpha slider of this : http://www.edumobile.org/iphone/how-to-make-an-app-2/controlling-a-uiviews-properties-for-ipad/ , but for a UIImageView. I promised i searched for hours , and didnt find how to do it ... Could someone have some minutes to give me ideas ?? Sorry for my poor english too. Thanks if you can. L. The resume of the link i posted, only focussing on the alpha property would be : ( considering a UIView ( View ) embeded in a ViewController ( ViewController ): enter code here ----View.h----- @interface View : UIView @property ( nonatomic, assign ) CGFloat alpha; @end enter code here ----View.m---- @implementation View @synthesize alpha; ?} @end enter code here ------ViewController.h----- import "View.h" @interface ViewController : UIViewController @property (nonatomic, strong) IBOutlet View *view; ?- (IBAction)alphaChanged:(UISlider *)sender; @end enter code here -------ViewController.m------ @interface ViewController () @end @implementation ViewController @synthesize view; (View *)view {?     if (!view) {?        view = [[View alloc] init];?    }?    return view;?} enter code here (IBAction)redChanged:(UISlider *)sender? {?    self.circle.alpha = sender.value;?    [self.circle setNeedsDisplay];?} (void)viewDidLoad ?{?    [super viewDidLoad];?         ?    self.circle.alpha = (CGFloat)1;?} (void)didReceiveMemoryWarning? {?  [super didReceiveMemoryWarning];?    @end enter code here

    Read the article

  • How to get drag working properly in silverlight when mouse is not pressed ?

    - by Mrt
    Hello, I have the following code xaml <Canvas x:Name="LayoutRoot" > <Rectangle Canvas.Left="40" Canvas.Top="40" Width="20" Height="20" Name="rec" Fill="Red" MouseLeftButtonDown="rec_MouseLeftButtonDown" MouseMove="rec_MouseMove" /> </Canvas> code behind public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } public Point LastDragPosition { get; set; } private bool isDragging; private void rec_MouseMove(object sender, MouseEventArgs e) { if(!isDragging) { return; } var position = e.GetPosition(rec as UIElement); var newPosition = new Point( Canvas.GetLeft(rec) + position.X - LastDragPosition.X, Canvas.GetTop(rec) + position.Y - LastDragPosition.Y); Canvas.SetLeft(rec, newPosition.X); Canvas.SetTop(rec, newPosition.Y); LastDragPosition = e.GetPosition(rec as UIElement); } private void rec_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { isDragging = true; LastDragPosition = e.GetPosition(sender as UIElement); rec.CaptureMouse(); } } This issue is the rectangle follows the mouse if the mouse left button is down, but I would like the rectangle to move even when the mouse left button isn't down. It works, but if you move the mouse very slowly. If you move the mouse to quickly the rectangle stops moving (is the mouse capture lost ?) Cheers,

    Read the article

  • no longer an issue

    - by MrTemp
    I am still new to c# and wpf This program is a clock with different view and I would like to use the context menu to change between view, but the error says that there is no definition or extension method for the events. Right now I have the event I'm working on popping up a MessageBox just so I know it has run, but I cannot get it to compile. public partial class MainWindow : NavigationWindow { public MainWindow() { //InitializeComponent(); } public void AnalogMenu_Click(object sender, RoutedEventArgs e) { /*AnalogClock analog = new AnalogClock(); this.NavigationService.Navigate(analog);*/ } public void DigitalMenu_Click(object sender, RoutedEventArgs e) { MessageBox.Show("Digital Clicked"); /*DigitalClock digital = new DigitalClock(); this.NavigationService.Navigate(digital);*/ } public void BinaryMenu_Click(object sender, RoutedEventArgs e) { /*BinaryClock binary = new BinaryClock(); this.NavigationService.Navigate(binary);*/ } } and the xaml call if you want it <NavigationWindow.ContextMenu> <ContextMenu Name="ClockMenu" > <MenuItem Name="ToAnalog" Header="To Analog" ToolTip="Changes to an analog clock"/> <MenuItem Name="ToDigital" Header="To Digital" ToolTip="Changes to a digital clock" Click="DigitalMenu_Click" /> <MenuItem Name="ToBinary" Header="To Binary" ToolTip="Changes to a binary clock"/> </ContextMenu> </NavigationWindow.ContextMenu>

    Read the article

  • TreeView Control Problem

    - by ProgNet
    Hi all, I have a public folder on the server that contains recursively nested sub folders. In the various Leaf folders contains Images. I wanted to create a server side file browser that will display the Images to the user. I am using the ASP.NET TreeView Control. I create the tree nodes using PopulateOnDemand. If the user click on a leaf directory I want the images in that folder to be displayed in a DataList Control. The problem is that when I click on a sub tree node (after I expanded it parent node) All the expanded sub tree disappears and only the parent node is showed with no + sign next to it !! ( I have set the TreeView's PopulateNodesFromClient property to true ) Can someone tell me what is the problem ?? Thanks Here is the code : <asp:TreeView ID="TreeView1" runat="server" AutoGenerateDataBindings="False" onselectednodechanged="TreeView1_SelectedNodeChanged" ontreenodepopulate="TreeView1_TreeNodePopulate"> </asp:TreeView> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string path = Server.MapPath("."); PopulateTopNodes(path); } } private void PopulateTopNodes(string pathToRootFolder) { DirectoryInfo dirInfo = new DirectoryInfo(pathToRootFolder); DirectoryInfo[] dirs = dirInfo.GetDirectories(); foreach (DirectoryInfo dir in dirs) { TreeNode folderNode = new TreeNode(dir.Name,dir.FullName); if (dir.GetDirectories().Length > 0) { folderNode.PopulateOnDemand = true; folderNode.Collapse(); } TreeView1.Nodes.Add(folderNode); } } protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e) { if (IsCallback == true) { if (e.Node.ChildNodes.Count == 0) { LoadChildNode(e.Node); } } } private void LoadChildNode(TreeNode treeNode) { DirectoryInfo dirInfo = new DirectoryInfo(treeNode.Value); DirectoryInfo[] dirs = dirInfo.GetDirectories(); foreach (DirectoryInfo dir in dirs) { TreeNode folderNode = new TreeNode(dir.Name, dir.FullName); if(dir.GetDirectories().Length>0){ folderNode.PopulateOnDemand = true; folderNode.Collapse(); } treeNode.ChildNodes.Add(folderNode); } } protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e) { // Retrieve the images here }

    Read the article

  • Page_Load or Page_Init

    - by balexandre
    Let's take a really simple example on using jQuery to ajaxify our page... $.load("getOrders.aspx", {limit: 25}, function(data) { // info as JSON is available in the data variable }); and in the ASP.NET (HTML part) page (only one line) <%@ Page Language="C#" AutoEventWireup="true" CodeFile="getOrders.aspx.cs" Inherits="getOrders" %> and in the ASP.NET (Code Behind) page public partial class getOrders : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string lmt = Request["limit"]; List<Orders> ords = dll.GetOrders(limit); WriteOutput( Newtonsoft.Json.JsonConvert.SerializeObject(ords) ); } private void WriteOutput(string s) { Response.Clear(); Response.Write(s); Response.Flush(); Response.End(); } } my question is Should it be protected void Page_Load(object sender, EventArgs e) or protected void Page_Init(object sender, EventArgs e) So we can save some milliseconds as we don't actually need to process the events for the page, or will Page_Init lack of some sorting of a method by the time it is called? P.S. Currently works fine in both methods, but I just want to understand the ins and outs of choosing one method over the other

    Read the article

  • How to draw mutiple rectangles using c#

    - by Nivas
    I have drawn and saved the Rectangle on the image i loaded in the picture box. How i like to draw multiple rectangles for that i tried array in the rectangle but it gives error ("Object reference not set to an instance of an object." (Null reference Exception was unhandled). enter code here private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (mybitmap == null) { mybitmap = new Bitmap(sz.Width, sz.Height); } rect = new Rectangle(e.X, e.Y, 0, 0); this.Invalidate(); } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (stayToolStripMenuItem.Checked == true) { switch (e.Button) { case MouseButtons.Left: { rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top); pictureBox1.Invalidate(); break; } } } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { if (stayToolStripMenuItem.Checked == true) { button1.Visible = true; button2.Visible = true; if (mybitmap == null) { return; } using (g = Graphics.FromImage(mybitmap)) { using (Pen pen = new Pen(Color.Red, 2)) { //g.Clear(Color.Transparent); e.Graphics.DrawRectangle(pen, rect); label1.Top = rect.Top; label1.Left = rect.Left; label1.Width = rect.Width; label1.Height = rect.Height; if (label1.TextAlign == ContentAlignment.TopLeft) { e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect); g.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect); g.DrawRectangle(pen, rect); } } } } } How can i do this.....

    Read the article

  • Can I get away with this or is it just too crude and unpractical ?

    - by The_AlienCoder
    I spent the whole of last night searching for a free AspNet web chat control that I could simply drag into my website. Well the search was in vain as I could not find a control that matched my needs i.e List of users, 1 to 1 chat, Ability to kick out users.. In the end I decided to create my own control from scractch. Although it works well on my machine Im concerned that It maybe a little crude and unpractical on a shared hosting enviroment. Basically this is what I did : Created an sql database that stores the chat messages. Wrote the stored procedures and and included a statement that clears old messages Then the 'crude' part : Dragged an update panel and timer control on my page Dragged a Repeater databound to the chat messages table inside the update panel Dragged another update panel and inside it put a textbox and a button Configured the timer control to tick every 5 seconds. ..and then I made it all work like this In the timer tick event I 'refreshed' the messages display by invoking Databind() on my repeater i.e protected void Timer1_Tick(object sender, EventArgs e) { MyRepeater.DataBind(); } Then in my send button click event protected void btnSend_Click(object sender, EventArgs e) { MyDataLayer.InsertMessage(Message, Sender, CurrTime); } Well It works well on my machine and Ive got the other functionalities(users list, kick out user..) to work by simply creating more tables. But like I said it seems a little crude to me. so I need a proffesional opinion. Should I run with this or try another Approach ?

    Read the article

< Previous Page | 20 21 22 23 24 25 26 27 28 29 30 31  | Next Page >