C# Windows form. How to use the button_click method? - visual-studio-2010

I am using a for loop to keep adding items to an array by keep pressing the button, i call it btnEnter, after input some data.
something like
double[] inputarr = new double[10];
for (int i = 0; i < inputarr.Length; i++)
{
inputarr[i] = Double.Parse(txtAmount.Text);
}
I want to jump out from the loop and perform something by clicking another button. Can button_click() do the job for me?
like
for (int i = 0; i < inputarr.Length; i++)
{
inputarr[i] = Double.Parse(txtAmount.Text);
if (btnStop_Click() == true)
{
break;
}
}
how to make this work? can anyone help me with this?

If I understand you correctly, you want to prompt for input 10 times in a row. You're thought process is a bit inverted. I think all you need is a prompt dialog. See Prompt Dialog in Windows Forms for an example.

You can call another button like this
for (int i = 0; i < inputarr.Length; i++)
{
inputarr[i] = Double.Parse(txtAmount.Text);
btnStop_Click(null,null);
break;
}
}
or u can use timer
int i = 0;Timer t = new Timer();
button_click(object sender,event e)
{
t.Interval = 4000;
t.Tick += t_Tick;
t.Start();
}
void t_Tick(object sender, EventArgs e)
{
if (i <= 9) { inputarr[i] = Double.Parse(txtAmount.Text); }
else { t.Stop(); Do other staff }
i++;
}

Related

How do the obstacle detection sensors work in the DJI Windows SDK?

I want to get the distance of the obstacles in the back and front of the Mavic Air.
I'm using the VissionDetectionStateChanged and it returns values in the 4 sectors, but all of them change only with obstacles in the back. If I put my hand in the front, nothing happens.
The VisionSensorPosition is returning TAIL always and when I put my hand very close to the tail of the aircraft it changes for NOSE.
Shouldn't be the opposite?
Right now I just display the information, but I'd like to be able to detect obstacles in the back and front of the aircraft to try to keep it in the middle of two objects and avoid collisions.
This is my code in the event:
private async void FlightAssistant_VissionDetectionStateChanged(object sender, VissionDetectionState? value)
{
if (value.HasValue)
{
if (txtPosition.Dispatcher.HasThreadAccess)
{
txtPosition.Text = value.Value.position.ToString();
for (int i = 0, count = value.Value.detectionSectors.Count; i < count; i++)
{
ObstacleDetectionSector sector = value.Value.detectionSectors[i];
TextBox txtWarning = this.FindControl<TextBox>("txtWarning" + i.ToString());
if (txtWarning != null)
txtWarning.Text = sector.warningLevel.ToString();
TextBox txtObstacleDistance = this.FindControl<TextBox>("txtObstacleDistance" + i.ToString());
if (txtObstacleDistance != null)
txtObstacleDistance.Text = sector.obstacleDistanceInMeters.ToString();
}
}
else
{
await txtPosition.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
txtIsSensorBeingUsed.Text = value.Value.isSensorBeingUsed.ToString();
txtPosition.Text = value.Value.position.ToString();
for (int i = 0, count = value.Value.detectionSectors.Count; i < count; i++)
{
ObstacleDetectionSector sector = value.Value.detectionSectors[i];
TextBox txtWarning = this.FindControl<TextBox>("txtWarning" + i.ToString());
if (txtWarning != null)
txtWarning.Text = sector.warningLevel.ToString();
TextBox txtObstacleDistance = this.FindControl<TextBox>("txtObstacleDistance" + i.ToString());
if (txtObstacleDistance != null)
txtObstacleDistance.Text = sector.obstacleDistanceInMeters.ToString();
}
});
}
}
}

winforms, help needed to create a dynamic tablelayoutpanel with buttons

I am trying to create a dynamic tablelayout which creates adds a skill and gives that skill 1 level and a increase decrease button. I am struggling with having the buttons access the level label. I thought about finding the location of the button that was clicked, but could figure out how to do that.
In advance, Thank you.
example:
1
this is what i have so far:
private void skilladded(object sender, EventArgs e)
{
int i = 1;
int[] position= { 0,0};
bool test = false;
//string select;
int k=0;
for (i=1;i<=skillstableLayoutPanel.RowCount;i++)
{
Control c= skillstableLayoutPanel.GetControlFromPosition(0,i);
if (c!=null&&addskillswin.selected==c.Text)
{
test = true;
k = i;
break;
}
else if(c==null)
{
k = i;
break;
}
}
if (test==false)
{
Label newskill = new Label();
Label newskilllvl = new Label();
TableLayoutPanel buttontable = new TableLayoutPanel();
Button up = new Button();
Button down = new Button();
buttontable.ColumnCount = 2;
buttontable.RowCount = 1;
buttontable.RowStyles.Add(new RowStyle(SizeType.Percent,100f));
buttontable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,50f));
buttontable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50f));
buttontable.Margin = new Padding(0,0,0,0);
buttontable.Dock = DockStyle.Fill;
buttontable.Controls.Add(up, 0, 0);
buttontable.Controls.Add(down, 1, 0);
up.BackgroundImage = Properties.Resources.up;[enter image description here][2]
down.BackgroundImage = Properties.Resources.down;
up.BackgroundImageLayout=ImageLayout.Stretch;
down.BackgroundImageLayout = ImageLayout.Stretch;
newskill.Text = addskillswin.selected;
newskilllvl.Text = "1";
up.Margin = new Padding(0, 0, 0, 0);
down.Margin = new Padding(0, 0, 0, 0);
skillstableLayoutPanel.Controls.Add(newskill,0,k);
skillstableLayoutPanel.Controls.Add(newskilllvl, 1, k);
skillstableLayoutPanel.Controls.Add(buttontable, 2, k);
skillavaillabel.Text = (Convert.ToInt32(skillavaillabel.Text) - 1).ToString();
skillpointlvl = Convert.ToInt32(newskilllvl.Text);
up.MouseClick += new MouseEventHandler(skillup);
down.MouseClick += new MouseEventHandler(skilldown);
}
if (test==true)
{
skillstableLayoutPanel.GetControlFromPosition(1, k).Text = (Convert.ToInt32(skillstableLayoutPanel.GetControlFromPosition(1, k).Text) + 1).ToString();
skillavaillabel.Text = (Convert.ToInt32(skillavaillabel.Text) -1).ToString();
}
}
private void skillup(object sender, EventArgs e)
{
skillpointlvl++;
}
private void skilldown(object sender, EventArgs e)
{
skillpointlvl--;
}
Instead of this:
up.MouseClick += new MouseEventHandler(skillup);
down.MouseClick += new MouseEventHandler(skilldown);
Try something like this:
up.MouseClick += ((o, me) =>
{
int currentLevel = Int32.Parse(newskilllvl.Text);
currentLevel++;
newskilllvl.Text = currentLevel.ToString();
});
down.MouseClick += ((o, me) =>
{
int currentLevel = Int32.Parse(newskilllvl.Text);
currentLevel--;
newskilllvl.Text = currentLevel.ToString();
});
Your skillup or skilldown event handler could potentially process each sender and see from which button the click originated, but you'd have to uniquely name each button and do a lot of string comparisons to see which button corresponds to which skill level label. The code above adds an anonymous handler to each button, which allows us to essentially tie the button being clicked to its corresponding skill label.
Personally though, I would not store all these values in labels like you have done. I would either store them in properties on the form, or better yet in a class of their own. I would also put all this logic somewhere else beside the form, like in a Presenter or Controller (or class library), and follow a design pattern such as MVC or MVP. This will make maintaining and changing the application easier in the long run.
Also, consider using camel case and Pascal case for your variable names. All lowercase variables are harder for experienced programmers to read.

Why I can't change style in mxEvent.CHANGE event first time?

I just want to change some style when the CHANGE event fired.But when I change the model by insert or move a vertex or edge, the style didn't change. And the changed vertex will change it's style after I change anything again. Is anybody konws why?
Here is my code:
graph.getModel().addListener(mxEvent.CHANGE, function(sender, evt){
if(graphInited){
graph.getModel().beginUpdate();
try {
var changes = evt.getProperty('edit').changes;
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
var state = graph.view.getState(change.cell);
if(state!=null){//color #1C86EE means new insert
if(state.style[mxConstants.STYLE_IMAGE_BACKGROUND]!="#1C86EE"
&& state.style[mxConstants.STYLE_STROKECOLOR]!="#1C86EE"
&& state.style[mxConstants.STYLE_FONTCOLOR]!="#1C86EE"){
graph.setCellStyles(mxConstants.STYLE_IMAGE_BACKGROUND, '#68228B', [change.cell]);
graph.setCellStyles(mxConstants.STYLE_STROKECOLOR, '#68228B', [change.cell]);
}
}
}
} finally {
graph.getModel().endUpdate();
}
}
});
I made more recon and fond simpler solution than in my first answer.
You need to add:
evt.consume()
graph.refresh()
So final code would looks like:
graph.getModel().addListener(mxEvent.CHANGE, function(sender, evt){
if(graphInited){
graph.getModel().beginUpdate();
evt.consume();
try {
var changes = evt.getProperty('edit').changes;
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
var state = graph.view.getState(change.cell);
if(state!=null){//color #1C86EE means new insert
if(state.style[mxConstants.STYLE_IMAGE_BACKGROUND]!="#1C86EE"
&& state.style[mxConstants.STYLE_STROKECOLOR]!="#1C86EE"
&& state.style[mxConstants.STYLE_FONTCOLOR]!="#1C86EE"){
graph.setCellStyles(mxConstants.STYLE_IMAGE_BACKGROUND, '#68228B', [change.cell]);
graph.setCellStyles(mxConstants.STYLE_STROKECOLOR, '#68228B', [change.cell]);
}
}
}
} finally {
graph.getModel().endUpdate();
graph.refresh();
}
}
});

How to correct loop counters for maze algorithm?

I have figured out how to move my character around the maze using the algorithm I have written, but the count is not figuring correctly. At the end of each row my character moves up and down several times until the count reaches the specified number to exit the loop, then the character moves along the next row down until it reaches the other side and repeats the moving up and down until the count reaches the specified number again. Can anyone help me find why my count keeps getting off? The algorithm and the maze class I am calling from is listed below.
public class P4 {
public static void main(String[] args) {
// Create maze
String fileName = args[3];
Maze maze = new Maze(fileName);
System.out.println("Maze name: " + fileName);
// Get dimensions
int mazeWidth = maze.getWidth();
int mazeHeight = maze.getHeight();
// Print maze size
System.out.println("Maze width: " + mazeWidth);
System.out.println("Maze height: " + mazeHeight);
int r = 0;
int c = 0;
// Move commands
while (true){
for (c = 0; c <= mazeWidth; c++){
if (maze.moveRight()){
maze.isDone();
c++;
}
if (maze.isDone() == true){
System.exit(1);
}
if (maze.moveRight() == false && c != mazeWidth){
maze.moveDown();
maze.moveRight();
maze.moveRight();
maze.moveUp();
c++;
}
}
for (r = 0; r % 2 == 0; r++){
maze.moveDown();
maze.isDone();
if (maze.isDone() == true){
System.exit(1);
}
}
for (c = mazeWidth; c >= 0; c--){
if (maze.moveLeft()){
c--;
maze.isDone();
System.out.println(c);
}
if (maze.isDone() == true){
System.exit(1);
}
if (maze.moveLeft() == false && c != 0){
maze.moveDown();
maze.moveLeft();
maze.moveLeft();
maze.moveUp();
c--;
}
}
for (r = 1; r % 2 != 0; r++){
maze.moveDown();
maze.isDone();
if (maze.isDone() == true){
System.exit(1);
}
}
}
}
}
public class Maze {
// Maze variables
private char mazeData[][];
private int mazeHeight, mazeWidth;
private int finalRow, finalCol;
int currRow;
private int currCol;
private int prevRow = -1;
private int prevCol = -1;
// User interface
private JFrame frame;
private JPanel panel;
private Image java, student, success, donotpass;
private ArrayList<JButton> buttons;
// Maze constructor
public Maze(String fileName) {
// Read maze
readMaze(fileName);
// Graphics setup
setupGraphics();
}
// Get height
public int getHeight() {
return mazeHeight;
}
// Get width
public int getWidth() {
return mazeWidth;
}
// Move right
public boolean moveRight() {
// Legal move?
if (currCol + 1 < mazeWidth) {
// Do not pass?
if (mazeData[currRow][currCol + 1] != 'D')
{
currCol++;
redraw(true);
return true;
}
}
return false;
}
// Move left
public boolean moveLeft() {
// Legal move?
if (currCol - 1 >= 0) {
// Do not pass?
if (mazeData[currRow][currCol - 1] != 'D')
{
currCol--;
redraw(true);
return true;
}
}
return false;
}
// Move up
public boolean moveUp() {
// Legal move?
if (currRow - 1 >= 0) {
// Do not pass?
if (mazeData[currRow - 1][currCol] != 'D')
{
currRow--;
redraw(true);
return true;
}
}
return false;
}
// Move down
public boolean moveDown() {
// Legal move?
if (currRow + 1 < mazeHeight) {
// Do not pass?
if (mazeData[currRow + 1][currCol] != 'D')
{
currRow++;
redraw(true);
return true;
}
}
return false;
}
public boolean isDone() {
// Maze solved?
if ((currRow == finalRow) && (currCol == finalCol))
return true;
else
return false;
}
private void redraw(boolean print) {
// Wait for awhile
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
if (print)
System.out.println("Moved to row " + currRow + ", column " + currCol);
// Compute index and remove icon
int index = (prevRow * mazeWidth) + prevCol;
if ((prevRow >= 0) && (prevCol >= 0)) {
buttons.get(index).setIcon(null);
}
// Compute index and add icon
index = (currRow * mazeWidth) + currCol;
if ((currRow == finalRow) && (currCol == finalCol))
buttons.get(index).setIcon(new ImageIcon(success));
else
buttons.get(index).setIcon(new ImageIcon(student));
// Store previous location
prevRow = currRow;
prevCol = currCol;
}
// Set button
private void setButton(JButton button, int row, int col) {
if (mazeData[row][col] == 'S') {
button.setIcon(new ImageIcon(student));
currRow = row;
currCol = col;
} else if (mazeData[row][col] == 'J') {
button.setIcon(new ImageIcon(java));
finalRow = row;
finalCol = col;
} else if (mazeData[row][col] == 'D') {
button.setIcon(new ImageIcon(donotpass));
}
}
// Read maze
private void readMaze(String filename) {
try {
// Open file
Scanner scan = new Scanner(new File(filename));
// Read numbers
mazeHeight = scan.nextInt();
mazeWidth = scan.nextInt();
// Allocate maze
mazeData = new char[mazeHeight][mazeWidth];
// Read maze
for (int row = 0; row < mazeHeight; row++) {
// Read line
String line = scan.next();
for (int col = 0; col < mazeWidth; col++) {
mazeData[row][col] = line.charAt(col);
}
}
// Close file
scan.close();
} catch (IOException e) {
System.out.println("Cannot read maze: " + filename);
System.exit(0);
}
}
// Setup graphics
private void setupGraphics() {
// Create grid
frame = new JFrame();
panel = new JPanel();
panel.setLayout(new GridLayout(mazeHeight, mazeWidth, 0, 0));
frame.add(Box.createRigidArea(new Dimension(0, 5)), BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
// Look and feel
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// Configure window
frame.setSize(mazeWidth * 100, mazeHeight * 100);
frame.setTitle("Maze");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
// Load and scale images
ImageIcon icon0 = new ImageIcon("Java.jpg");
Image image0 = icon0.getImage();
java = image0.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon1 = new ImageIcon("Student.jpg");
Image image1 = icon1.getImage();
student = image1.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon2 = new ImageIcon("Success.jpg");
Image image2 = icon2.getImage();
success = image2.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon3 = new ImageIcon("DoNotPass.jpg");
Image image3 = icon3.getImage();
donotpass = image3.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
// Build panel of buttons
buttons = new ArrayList<JButton>();
for (int row = 0; row < mazeHeight; row++) {
for (int col = 0; col < mazeWidth; col++) {
// Initialize and add button
JButton button = new JButton();
Border border = new LineBorder(Color.darkGray, 4);
button.setOpaque(true);
button.setBackground(Color.gray);
button.setBorder(border);
setButton(button, row, col);
panel.add(button);
buttons.add(button);
}
}
// Show window
redraw(false);
frame.setVisible(true);
}
}
One error I can see in your code is that you're incrementing your c counter more often than you should. You start with it managed by your for loop, which means that it will be incremented (or decremented, for the leftward moving version) at the end of each pass through the loop. However, you also increment it an additional time in two of your if statements. That means that c might increase by two or three on a single pass through the loop, which is probably not what you intend.
Furthermore, the count doesn't necessarily have anything obvious to do with the number of moves you make. The loop code will always increase it by one, even if you're repeatedly trying to move through an impassible wall.
I don't really understand what your algorithm is supposed to be, so I don't have any detailed advice for how to fix your code.
One suggestion I have though is that you probably don't ever want to be calling methods on your Maze class without paying attention to their return values. You have a bunch of places where you call isDone but ignore the return value, which doesn't make any sense. Similarly, you should always be checking the return values from your moveX calls, to see if the move was successful or not. Otherwise you may just blunder around a bunch, without your code having any clue where you are in the maze.

WP7 Textbox with title inside of textbox

I would like to have a textbox that lets a user enter some text (obviously). Let's say it's 'Title'. Is there a pre-built control that shows the name of the field (Title in this case) inside of the text box and then have it clear out when the user enter the field. Example: The search box at the top of this page has 'Search' but when you enter the box it goes away.
Watermarked TextBox
I think I remember it also being in the Mango Silverlight Toolkit too, correct me if I'm wrong:
Mango Silverlight Toolkit
This is an example. Put the GotFocus and LostFocus event in your textbox(in .xaml page).
<TextBox x:Name="UrlTextBox" Text="Search" Margin="0,0,98,0" GotFocus="UrlTextBox_GotFocus" LostFocus="UrlTextBox_LostFocus"/>
In xaml.cs page, add the following codes-
private void UrlTextBox_GotFocus(object sender, RoutedEventArgs e)
{
if (UrlTextBox.Text == "Search")
{
UrlTextBox.Text = "";
SolidColorBrush Brush1 = new SolidColorBrush();
Brush1.Color = Colors.Gray;
UrlTextBox.Foreground = Brush1;
}
else
{
char[] strDataAsChars = UrlTextBox.Text.ToCharArray();
int i = 0;
for (i = UrlTextBox.SelectionStart - 1; ((i >= 0) &&
(strDataAsChars[i] != ' ')); --i) ;
int selBegin = i + 1;
for (i = UrlTextBox.SelectionStart; ((i < strDataAsChars.Length) &&
(strDataAsChars[i] != ' ')); ++i) ;
int selEnd = i;
UrlTextBox.Select(selBegin, selEnd - selBegin);
}
}
private void UrlTextBox_LostFocus(object sender, RoutedEventArgs e)
{
if (UrlTextBox.Text == String.Empty)
{
UrlTextBox.Text = "Search";
SolidColorBrush Brush2 = new SolidColorBrush();
Brush2.Color = Colors.Gray;
UrlTextBox.Foreground = Brush2;
}
}

Resources