How to alternate between button click even handlers [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am creating a desktop application that adds/edits users. Both functions will use the same inputs however each function will require different click handlers to update data and to insert new data into my database however I want to utilize the same buttons
Is their a way I can assign different click handlers to the same button?

Yes you can,
//Register both handlers within constructor
button1.Click += new EventHandler(InsertOperationHandler);
button1.Click += new EventHandler(UpdateOperationHandler);
-
private void InsertOperationHandler(object sender, EventArgs e)
{
}
private void UpdateOperationHandler(object sender, EventArgs e)
{
}

The solution I came up with is as follows:
public void displayEditButtons()
{
buttonPeopleOne.Text = "Save Changes";
this.buttonPeopleOne.Click -= new System.EventHandler(this.buttonPeopleOneClear_Click);
this.buttonPeopleOne.Click += new System.EventHandler(this.buttonPeopleOneSave_Click);
buttonPeopleTwo.Text = "Delete User";
this.buttonPeopleTwo.Click -= new System.EventHandler(this.buttonPeopleTwoNext_Click);
this.buttonPeopleTwo.Click += new System.EventHandler(this.buttonPeopleTwoDelete_Click);
//change other controls to match the function context
buttonPeopleChangeFunction.Visible = true;
this.labelPeopleFunctionHeader.Text = "Edit Current User";
}
public void displayAddButtons()
{
buttonPeopleOne.Text = "Clear";
this.buttonPeopleOne.Click -= new System.EventHandler(this.buttonPeopleOneSave_Click);
this.buttonPeopleOne.Click += new System.EventHandler(this.buttonPeopleOneClear_Click);
buttonPeopleTwo.Text = "Add Contact";
this.buttonPeopleTwo.Click -= new System.EventHandler(this.buttonPeopleTwoDelete_Click);
this.buttonPeopleTwo.Click += new System.EventHandler(this.buttonPeopleTwoNext_Click);
//change other controls to match the function context
buttonPeopleChangeFunction.Visible = false;
this.labelPeopleFunctionHeader.Text = "Add New User";
}
I simply call the different methods when I need to change the buttons

Related

C# Button Too each Music [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I had some difficulty trying to make my program make buttons for each song, like say I have 6 songs in a folder, what program should do is get them all in and generate button to each song and when I press them they will play their own song. I can't really even think where to start at this point, I got FolderBrowsingDiaglog running I just need to figure this part out. I added the code that you gave me and it gives me an error of that i have illegal characters in path.
private void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderChoice = new FolderBrowserDialog();
if (folderChoice.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int i = 0;
foreach (string fname in System.IO.Directory.GetFiles(folderChoice.SelectedPath + #"*.mp3"))
{
Button btn = new Button
{
Text = fname.Split('\\').LastOrDefault(),
Location = new Point(10, 10 + i++ * 30), //sample x,y
Size = new Size(100, 20),
Tag = fname, //For having the file location
};
this.Controls.Add(btn);
}
}
}
Well creating buttons is easy:
if(folderBrDlg.ShowDialog()==DialogResult.Ok)
{
int i = 0;
foreach(string fname in System.IO.Directory.GetFiles())
{
Button btn = new Button
{
Text = fname.Split('\\').LastOrDefault(),
Location = new Point(10, 10 + i++ * 30), //sample x,y
Size = new Size(100,20),
Tag = fname, //For having the file location
....
};
btn.Click += (s, e) =>
{
string fileToPlay = (string)((Button)s).Tag;
//now you only have to play it.
}
this.Controls.Add(btn);
}
}
Update:
I added the click event for the button to that on click of every button you can get the path of the related file, and you just have to use a player to play it.
This is my understanding of the question.
1. You want to make a program that plays one of your six songs when one of the buttons are clicked
FolderbrowsingDialog will allow to choose the files you want to play but it won't let you play them. Consider using the SoundPlayer class. SoundPlayer will give you the functionality to play the songs but these songs need to be .wav files.The microsoft link will help you get a better about the SoundPlayer class.
From this you should be able to finish your program.
https://learn.microsoft.com/en-us/dotnet/api/system.media.soundplayer?redirectedfrom=MSDN&view=netframework-4.7.2

How to use ZK4500 Fingerprint Scanner SDK in C# Project [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am developing a project in C#, for which I want to login/authenticate a user using their fingerprint.
I bought a ZK4500 Fingerprint scanner and got its SDK from http://www.zkteco.com/product/ZK4500_238.html. The SDK is in C++.
So How can I integrate this SDK with my C# project to perform the desired functionality?
You need to add reference to ZKFPEngXControl that will appear under COM Type Libraries. After that you can use the ZKFPEngX Class to do whatever you require.
using ZKFPEngXControl;
and then
ZKFPEngX fp = new ZKFPEngX();
fp.SensorIndex = 0;
fp.InitEngine(); // Do validation as well as it returns an integer (0 for success, else error code 1-3)
//subscribe to event for getting when user places his/her finger
fp.OnImageReceived += new IZKFPEngXEvents_OnImageReceivedEventHandler(fp_OnImageReceived);
You can write your own method fp_OnImageReceived to handle the event. for example you can write this in that method;
object imgdata = new object();
bool b = fp.GetFingerImage(ref imgdata);
Where imgdata is an array of bytes.You can also use other methods in ZKFPEngX, to achieve your goals. Remember to close the engine when form closes.
fp.EndEngine();
You can store a fingerprint under OnEnroll(bool ActionResult, object ATemplate) Event.This event will be called when BeginEnroll() has been executed.
//Add an event handler on OnEnroll Event
ZKFPEngX x = new ZKFPEngX();
x.OnEnroll += X_OnEnroll;
private void X_OnEnroll(bool ActionResult, object ATemplate)
{
if (ActionResult)
{
if (x.LastQuality >= 80) //to ensure the fingerprint quality
{
string regTemplate = x.GetTemplateAsStringEx("9");
File.WriteAllText(Application.StartupPath + "\\fingerprint.txt", regTemplate);
}
else
{
//Quality is too low
}
}
else
{
//Register Failed
}
}
You can try to verify the fingerprints under OnCapture(bool ActionResult, object ATemplate)event. This event will be called when a finger is put on the scanner.
Add an event handler on OnCapture Event:
x.OnCapture += X_OnCapture;
Verify the fingerprints when the event has been called (a finger is put on the scanner):
private void X_OnCapture(bool ActionResult, object ATemplate)
{
if (ActionResult) //if fingerprint is captured successfully
{
bool ARegFeatureChanged = true;
string regTemplate = File.ReadAllText(Application.StartupPath + "\\fingerprint.txt");
string verTemplate = x.GetTemplateAsString();
bool result = x.VerFingerFromStr(regTemplate , verTemplate, false, ARegFeatureChanged);
if (result)
{
//matched
}
else
{
//not matched
}
}
else
{
//failed to capture a valid fingerprint
}
}

Using C# & Xamarin Forms - How can I close one modal without setting of chain of closures

In one stage of my app (Android & iOS are the ones we care about) we've got three pages which take in details and then open a webView for the user to input their card details to take a payment - this can't be done in the app due to Apple's guidelines.
I need to format the navigation in a way that when the user has finished in the webView it closes and then closes the 3 previous modals to get back to the original page. I've got it all working with the Appearing event so each page just closes itself:
this.Appearing += async (s, e) =>
{
await Navigation.PopModalAsync();
};
The issue I'm now having is that when the user presses the back button on the phone, it closes all of the pages that they've been through already & back to the original. I thought about implementing a custom nav bar and disabling the back button on the hardware but this would cause the same problem with the Appearing event.
Is there any easy way to solve this?
EDIT: Relevant code;
async void OnButtonClicked(object sender, EventArgs eventArgs)
{
if (IsConnected)
{
ActivityIndicator.IsVisible = true;
var button = (Button) sender;
button .IsEnabled = false;
await Navigation.PushModalAsync(new Page());
this.Appearing += (s, e) =>
{
ActivityIndicator.IsVisible = false;
button.IsEnabled = true;
RefreshPage();
};
}
else
{
NoInternetLabel.IsVisible = true;
}
}
Use this:
YourButton.Clicked += OpenPage;
OpenPage looks like this:
async public void OpenPage(object sender, EventArgs args)
{
await Navigation.PushAsync(new PageToShow());
}
You don't have to do anything to handle the PageToShow() closing, that happens by itself when the user presses the back button.
Managed to solve this by using Actions. In each new Page() we passed up an async method to close it once the one after had completed;
var nextPage = new Page(async () =>
{
await Navigation.PopModalAsync();
_completedSuccessfully();
});
await Navigation.PushModalAsync(nextPage);
And in the new page class;
private readonly Action _completedSuccessfully;
public Page(Action completedSuccessfully)
{
_completedSuccessfully = completedSuccessfully;
}
This meant that when the webView closed it called the completedSuccessfully() action and then chained all of them to the original page.

MultiThreading in winform c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I Want to know that i have define a function in form
Eg:Dynamically Display (Running) Current Date Time
It display the current system time on that form
Is it possible to call the same function without creating a new function on each and every form?
please help
Solution 1: You dont need to write a function for this:
Label1.Text = DateTime.Now.ToString();
Solution 2: but if you want to access it using function create a static function
public static class Utility
{
public static string DisplayDateTime()
{
return DateTime.Now.ToString();
}
}
Call the above function wherever you want as below:
Label1.Text = Utility.DisplayDateTime();
Solution 3: if you want to change datetime for every second try this:
public static class Utility
{
public static string DisplayDateTime()
{
return DateTime.Now.ToString();
}
}
System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
timer1.Interval=1000;//one second
timer1.Tick += new System.EventHandler(timer1_Tick);
timer1.Start();
private void timer1_Tick(object sender, EventArgs e)
{
//do whatever you want
Label1.Text = Utility.DisplayDateTime();
}

C# APP freezes during runtime [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Here is the code, I have tested the snmpconn method in a commandline application it works but it freezes during runtime in windows form application, I have no reason why ?
public snmpmain()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.button1.Click += new System.EventHandler(this.snmpconn);
}
private void button1_Click(object sender, EventArgs e)
{
//button1.Enabled = false; will disable the button before the event is fired
this.button1.Click += new System.EventHandler(this.snmpconn);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
int port = 162;
// UdpClient listener;
// IPEndPoint groupEP;
byte[] packet = new byte[1024];
int commlength, miblength, datatype, datalength, datastart, Objecttype, Objectlength;
int agent;
int timestamp;
int entrspc;
int specifictrap;
int finallen;
int objectstart;
string objectid;
string test1;
byte[] test2 = new byte[1024];
int temp;
string tempo;
private void snmpconn(object sender, System.EventArgs e)
{
listBox1.Items.Add("Initializing" + port + "...");
this.button1.Click -= new System.EventHandler(this.snmpconn);
UdpClient listener = new UdpClient(port);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, port);
while (true)
{
listBox1.Items.Add("Waiting....");
packet = listener.Receive(ref groupEP);
listBox1.Items.Add("Processing...");
if (packet.Length != 0)
{ // do some work
}
}
}
This works well with command line application.
Do you have a clue .
Woah, i answered without noticing the main mistake!!
while (true)
Please, don't do it, almost never, if you're not sure of what you're doing!!
You're allocating 100% resources of your process while standing in that loop, without ever leaving a single bit of CPU to perform rendering.
You should read & learn about multi-threading & synchronization before an attempt to make your code working fine.
Then, you're binding too much events to your btn click!
This row:
this.button1.Click += new System.EventHandler(this.snmpconn);
is not necessary on button1_Click event.
Also, playing with binding events on click may be misleading, you could use a flag (true/false) to check whether to perform your function when btn is clicked.

Categories

Resources