I have just started learning kinect, and I tried following one of the examples online, but I am returned this error:
No overload for 'msfr_MultiSourceFrameArrived matches delegate 'TypedEventHandler'
I pointed out where the error line is at in the code, which is above the sensor.Open in MainPage
How my code looks like :
KinectSensor sensor;
InfraredFrameReader irReader;
ushort[] irData;
byte[] irDataConverted;
WriteableBitmap irBitmap;
Body[] bodies;
MultiSourceFrameReader msfr;
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
sensor = KinectSensor.GetDefault();
irReader = sensor.InfraredFrameSource.OpenReader();
FrameDescription fd = sensor.InfraredFrameSource.FrameDescription;
irData = new ushort[fd.LengthInPixels];
irDataConverted = new byte[fd.LengthInPixels * 4];
irBitmap = new WriteableBitmap(fd.Width, fd.Height);
image.Source = irBitmap;
bodies = new Body[6];
msfr = sensor.OpenMultiSourceFrameReader(FrameSourceTypes.Body| FrameSourceTypes.Infrared);
msfr.MultiSourceFrameArrived += msfr_MultiSourceFrameArrived; <-- the error
sensor.Open();
}
void msfr_MultiSourceFrameArrived(MultiSourceFrameReader sender, MultiSourceFrame args)
{
using (MultiSourceFrame msf = args.BodyFrameReference.AcquireFrame())
{
if (msf != null)
{
using (BodyFrame bodyFrame = msf.BodyFrameReference.AcquireFrame())
{
using (InfraredFrame irFrame = msf.InfraredFrameReference.AcquireFrame())
{
if (bodyFrame != null && irFrame != null)
{
irFrame.CopyFrameDataToArray(irData);
for (int i = 0; i < irData.Length; i++)
{
byte intensity = (byte)(irData[i] >> 8);
irDataConverted[i * 4] = intensity;
irDataConverted[i * 4 + 1] = intensity;
irDataConverted[i * 4 + 2] = intensity;
irDataConverted[i * 4 + 3] = 255;
}
irDataConverted.CopyTo(irBitmap.PixelBuffer);
irBitmap.Invalidate();
bodyFrame.GetAndRefreshBodyData(bodies);
bodyCanvas.Children.Clear();
foreach (Body body in bodies)
{
if (body.IsTracked)
{
Joint headJoint = body.Joints[JointType.Head];
if (headJoint.TrackingState == TrackingState.Tracked)
{
DepthSpacePoint dsp = sensor.CoordinateMapper.MapCameraPointsToDepthSpace(headJoint.Position);
Ellipse headCircle = new Ellipse() { Width = 50, Height = 50, Fill = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)) };
bodyCanvas.Children.Add(headCircle);
Canvas.SetLeft(headCircle, dsp.X-25);
Canvas.SetTop(headCircle, dsp.Y-25);
}
}
}
}
}
}
}
}
}
Try changing the argument in msfr_MultiSourceFrameArrived() from MultiSourceFrame args to MultiSourceFrameArrivedEventArgs args
The MultiSourceFrameArrived event of the FrameReader is expecting a specific type of eventhandler argument and it's telling you the one you currently use is not what it's expecting.
Related
I want to make a bitmap and save it and display it. I can display it but I cannot save it.
I get this runtime error : System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI+.'
I am even using using and I still get that error
private void button1_Click(object sender, EventArgs e)
{
byte[] returndata = new byte[7057600];
for (int x = 0; x < returndata.Length; )
{
returndata[x] = 255;
returndata[x + 1] = 255;
returndata[x + 2] = 0;
returndata[x + 3] = 0;
x = x + 4;
}
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
saveFileDialog1.Filter = "Bitmaps|*.bmp";
Bitmap temp = null;
temp = InttoBitmap(returndata);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string location = saveFileDialog1.FileName;
temp.Save(location, ImageFormat.Bmp);
pictureBox1.Image = temp;
}
}
}
int keepWidth = 3208;
int keepHeight = 2200;
public Bitmap InttoBitmap(byte[] array)
{
unsafe
{
IntPtr pixptr = Marshal.AllocHGlobal(keepWidth * keepHeight * 4);
Marshal.Copy(array, 0, pixptr, keepWidth * keepHeight);
Bitmap bitmap = new Bitmap(keepWidth, keepHeight, 2 * keepWidth, System.Drawing.Imaging.PixelFormat.Format24bppRgb, pixptr);
return bitmap;
}
}
I'm using MaterialSkin UI controls , how can I change the control properties to Right to left, because it's by default Left to Right.
I think this is the code should be edited :
private void UpdateTabRects()
{
_tabRects = new List<Rectangle>();
//If there isn't a base tab control, the rects shouldn't be calculated
//If there aren't tab pages in the base tab control, the list should just be empty which has been set already; exit the void
if (_baseTabControl == null || _baseTabControl.TabCount == 0) return;
//Calculate the bounds of each tab header specified in the base tab control
using (var b = new Bitmap(1, 1))
{
using (var g = Graphics.FromImage(b))
{
_tabRects.Add(new Rectangle(SkinManager.FormPadding, 0, TabHeaderPadding * 2 + (int)g.MeasureString(_baseTabControl.TabPages[0].Text, SkinManager.Font_Size11).Width, Height));
for (int i = 1; i < _baseTabControl.TabPages.Count; i++)
{
_tabRects.Add(new Rectangle(_tabRects[i - 1].Right, 0, TabHeaderPadding * 2 + (int)g.MeasureString(_baseTabControl.TabPages[i].Text , SkinManager.Font_Size11).Width , Height));
}
}
}
}
and this is the full code for the control :
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms;
using MaterialSkin.Animations;
namespace MaterialSkin.Controls
{
public class MaterialTabSelector : Control, IMaterialControl
{
[Browsable(false)]
public int Depth { get; set; }
[Browsable(false)]
public MaterialSkinManager SkinManager => MaterialSkinManager.Instance;
[Browsable(false)]
public MouseState MouseState { get; set; }
private MaterialTabControl _baseTabControl;
public MaterialTabControl BaseTabControl
{
get { return _baseTabControl; }
set
{
_baseTabControl = value;
if (_baseTabControl == null) return;
_previousSelectedTabIndex = _baseTabControl.SelectedIndex;
_baseTabControl.Deselected += (sender, args) =>
{
_previousSelectedTabIndex = _baseTabControl.SelectedIndex;
};
_baseTabControl.SelectedIndexChanged += (sender, args) =>
{
_animationManager.SetProgress(0);
_animationManager.StartNewAnimation(AnimationDirection.In);
};
_baseTabControl.ControlAdded += delegate
{
Invalidate();
};
_baseTabControl.ControlRemoved += delegate
{
Invalidate();
};
}
}
private int _previousSelectedTabIndex;
private Point _animationSource;
private readonly AnimationManager _animationManager;
private List<Rectangle> _tabRects;
private const int TabHeaderPadding = 24;
private const int TabIndicatorHeight = 2;
public MaterialTabSelector()
{
SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer, true);
Height = 48;
_animationManager = new AnimationManager
{
AnimationType = AnimationType.EaseOut,
Increment = 0.04
};
_animationManager.OnAnimationProgress += sender => Invalidate();
}
protected override void OnPaint(PaintEventArgs e)
{
var g = e.Graphics;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.Clear(SkinManager.ColorScheme.PrimaryColor);
if (_baseTabControl == null) return;
if (!_animationManager.IsAnimating() || _tabRects == null || _tabRects.Count != _baseTabControl.TabCount)
UpdateTabRects();
var animationProgress = _animationManager.GetProgress();
//Click feedback
if (_animationManager.IsAnimating())
{
var rippleBrush = new SolidBrush(Color.FromArgb((int)(51 - (animationProgress * 50)), Color.White));
var rippleSize = (int)(animationProgress * _tabRects[_baseTabControl.SelectedIndex].Width * 1.75);
g.SetClip(_tabRects[_baseTabControl.SelectedIndex]);
g.FillEllipse(rippleBrush, new Rectangle(_animationSource.X - rippleSize / 2, _animationSource.Y - rippleSize / 2, rippleSize, rippleSize));
g.ResetClip();
rippleBrush.Dispose();
}
//Draw tab headers
foreach (TabPage tabPage in _baseTabControl.TabPages)
{
var currentTabIndex = _baseTabControl.TabPages.IndexOf(tabPage);
Brush textBrush = new SolidBrush(Color.FromArgb(CalculateTextAlpha(currentTabIndex, animationProgress), SkinManager.ColorScheme.TextColor));
g.DrawString(tabPage.Text.ToUpper(), SkinManager.Font_Size11, textBrush, _tabRects[currentTabIndex], new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
textBrush.Dispose();
}
//Animate tab indicator
var previousSelectedTabIndexIfHasOne = _previousSelectedTabIndex == -1 ? _baseTabControl.SelectedIndex : _previousSelectedTabIndex;
var previousActiveTabRect = _tabRects[previousSelectedTabIndexIfHasOne];
var activeTabPageRect = _tabRects[_baseTabControl.SelectedIndex];
var y = activeTabPageRect.Bottom - 2;
var x = previousActiveTabRect.X + (int)((activeTabPageRect.X - previousActiveTabRect.X) * animationProgress);
var width = previousActiveTabRect.Width + (int)((activeTabPageRect.Width - previousActiveTabRect.Width) * animationProgress);
g.FillRectangle(SkinManager.ColorScheme.AccentBrush, x, y, width, TabIndicatorHeight);
}
private int CalculateTextAlpha(int tabIndex, double animationProgress)
{
int primaryA = SkinManager.ActionBarText.A;
int secondaryA = SkinManager.ActionBarTextSecondary.A;
if (tabIndex == _baseTabControl.SelectedIndex && !_animationManager.IsAnimating())
{
return primaryA;
}
if (tabIndex != _previousSelectedTabIndex && tabIndex != _baseTabControl.SelectedIndex)
{
return secondaryA;
}
if (tabIndex == _previousSelectedTabIndex)
{
return primaryA - (int)((primaryA - secondaryA) * animationProgress);
}
return secondaryA + (int)((primaryA - secondaryA) * animationProgress);
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (_tabRects == null) UpdateTabRects();
for (var i = 0; i < _tabRects.Count; i++)
{
if (_tabRects[i].Contains(e.Location))
{
_baseTabControl.SelectedIndex = i;
}
}
_animationSource = e.Location;
}
private void UpdateTabRects()
{
_tabRects = new List<Rectangle>();
//If there isn't a base tab control, the rects shouldn't be calculated
//If there aren't tab pages in the base tab control, the list should just be empty which has been set already; exit the void
if (_baseTabControl == null || _baseTabControl.TabCount == 0) return;
//Calculate the bounds of each tab header specified in the base tab control
using (var b = new Bitmap(1, 1))
{
using (var g = Graphics.FromImage(b))
{
_tabRects.Add(new Rectangle(SkinManager.FormPadding, 0, TabHeaderPadding * 2 + (int)g.MeasureString(_baseTabControl.TabPages[0].Text, SkinManager.Font_Size11).Width, Height));
for (int i = 1; i < _baseTabControl.TabPages.Count; i++)
{
_tabRects.Add(new Rectangle(_tabRects[i - 1].Right, 0, TabHeaderPadding * 2 + (int)g.MeasureString(_baseTabControl.TabPages[i].Text , SkinManager.Font_Size11).Width , Height));
}
}
}
}
}
}
If you're using windows forms you would go into the properties of the tab control and make:
RightToLeft = Yes
and
RightToLeftLayout = True.
This is also a duplicate question:
How to make Managed Tab Control (MTC) appear right to left
I am working modifying an application that will be an utility. The application is designed so far to load pictures from any folder and show them in thumbnails, then the user should be able to select those that will want to save in a database. The thumbnails consists of an ImageViewer form that will load each image. Thus, in the ImageViewer form there is a textbox and a checkbox. Each of them will be generated dynamically as many pictures are loaded (see the image below). The problem is that when clicking the checkbox it should show the name listed above the picture (thumbnail textbox) of the file in a label (it can be a label or textbox). Any time when the user clicks the checkbox will see a message saying: 'Added anyImage.jpg' or when deselecting the checkbox will say 'Removed anyImage.jpg'. It is not showing the text in the label. I have the following code.
This code is to load the main form:
public MainForm()
{
InitializeComponent();
Login loginSystem = new Login();
lbHowMany.Visible = false;
lbHowMany.Text = "Images";
lbNumberOfFiles.Visible = false;
btnEnableViewer.Text = "Disable Viewer";
this.buttonCancel.Enabled = false;
//stripSelectedFile.Text = "";
m_ImageDialog = new ImageDialog();
m_AddImageDelegate = new DelegateAddImage(this.AddImage);
m_Controller = new ThumbnailController();
m_Controller.OnStart += new ThumbnailControllerEventHandler(m_Controller_OnStart);
m_Controller.OnAdd += new ThumbnailControllerEventHandler(m_Controller_OnAdd);
m_Controller.OnEnd += new ThumbnailControllerEventHandler(m_Controller_OnEnd);
if (ImageViewer.sendSelectedFile != null)
{
stripSelectedFile.Text = ImageViewer.sendSelectedFile.ToString();
txInformation.Text = ImageViewer.sendSelectedFile.ToString();
}
}
This other code is from the ImageViewer form checkbox:
public void cboxToSave_CheckedChanged(object sender, EventArgs e)
{
if (cboxToSave.Checked == true)
{
sendSelectedFile = "Added: " + txFileName.Text;
}
else
{
{
sendSelectedFile = "Removed: " + txFileName.Text;
}
}
}
This is the variable declared in the class that will send the selected file name to the main form: public static string sendSelectedFile;
ImageViewer Code:
public partial class ImageViewer : UserControl
{
private Image m_Image;
private string m_ImageLocation;
private bool m_IsThumbnail;
private bool m_IsActive;
public static string sendSelectedFile;
public ImageViewer()
{
m_IsThumbnail = false;
m_IsActive = false;
InitializeComponent();
}
public Image Image
{
set
{
m_Image = value;
}
get
{
return m_Image;
}
}
public string ImageLocation
{
set
{
m_ImageLocation = value;
}
get
{
return m_ImageLocation;
}
}
public bool IsActive
{
set
{
m_IsActive = value;
this.Invalidate();
}
get
{
return m_IsActive;
}
}
public bool IsThumbnail
{
set
{
m_IsThumbnail = value;
}
get
{
return m_IsThumbnail;
}
}
public void ImageSizeChanged(object sender, ThumbnailImageEventArgs e)
{
this.Width = e.Size;
this.Height = e.Size;
this.Invalidate();
}
public void LoadImage(string imageFilename, int width, int height)
{
Image tempImage = Image.FromFile(imageFilename);
m_ImageLocation = imageFilename;
//gets the name of the file from the location
txFileName.Text = Path.GetFileNameWithoutExtension(imageFilename);
int dw = tempImage.Width;
int dh = tempImage.Height;
int tw = width;
int th = height;
double zw = (tw / (double)dw);
double zh = (th / (double)dh);
double z = (zw <= zh) ? zw : zh;
dw = (int)(dw * z);
dh = (int)(dh * z);
m_Image = new Bitmap(dw, dh);
Graphics g = Graphics.FromImage(m_Image);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(tempImage, 0, 0, dw, dh);
g.Dispose();
tempImage.Dispose();
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
if (g == null) return;
if (m_Image == null) return;
int dw = m_Image.Width;
int dh = m_Image.Height;
int tw = this.Width - 8; // remove border, 4*4
int th = this.Height - 8; // remove border, 4*4
double zw = (tw / (double)dw);
double zh = (th / (double)dh);
double z = (zw <= zh) ? zw : zh;
dw = (int)(dw * z);
dh = (int)(dh * z);
int dl = 4 + (tw - dw) / 2; // add border 2*2
int dt = 4 + (th - dh) / 2; // add border 2*2
g.DrawRectangle(new Pen(Color.Yellow), dl, dt, dw, dh);
if (m_IsThumbnail)
for (int j = 0; j < 3; j++)
{
//draws and color the horizontal line in the miniature
g.DrawLine(new Pen(Color.LightSalmon),
new Point(dl + 3, dt + dh + 1 + j),
new Point(dl + dw + 3, dt + dh + 1 + j));
//draws and color the vertical right line in the miniature
g.DrawLine(new Pen(Color.LightGreen),
new Point(dl + dw + 1 + j, dt + 3),
new Point(dl + dw + 1 + j, dt + dh + 3));
}
g.DrawImage(m_Image, dl, dt, dw, dh);
if (m_IsActive)
{
//draws the rectangle inside and gives it color
g.DrawRectangle(new Pen(Color.MediumTurquoise, 1), dl, dt, dw, dh);
//draws the rectangle outside and gives it color
g.DrawRectangle(new Pen(Color.RosyBrown, 2), dl - 2, dt - 2, dw + 4, dh + 4);
}
}
private void OnResize(object sender, EventArgs e)
{
this.Invalidate();
}
public void cboxToSave_CheckedChanged(object sender, EventArgs e)
{
if (cboxToSave.Checked == true)
{
sendSelectedFile = "Added: " + txFileName.Text;
}
else
{
{
sendSelectedFile = "Removed: " + txFileName.Text;
}
}
}
}
Code in the MainForm that adds the images in the flowLayoutPanelMain
delegate void DelegateAddImage(string imageFilename);
private DelegateAddImage m_AddImageDelegate;
private void AddImage(string imageFilename)
{
try
{
// thread safe
if (this.InvokeRequired)
{
this.Invoke(m_AddImageDelegate, imageFilename);
}
else
{
int size = ImageSize;
lbNumberOfFiles.Visible = true;
lbHowMany.Visible = true;
ImageViewer imageViewer = new ImageViewer();
imageViewer.Dock = DockStyle.Bottom;
imageViewer.LoadImage(imageFilename, 256, 256);
imageViewer.Width = size;
imageViewer.Height = size;
imageViewer.IsThumbnail = true;
imageViewer.MouseClick += new MouseEventHandler(imageViewer_MouseClick);
txInformation.Text = imageFilename;
SetProgressBar();
counter++;
lbHowMany.Text = "Images";
lbNumberOfFiles.Text = counter.ToString();
this.OnImageSizeChanged += new ThumbnailImageEventHandler(imageViewer.ImageSizeChanged);
//passes the pictures to the main picture container
this.flowLayoutPanelMain.Controls.Add(imageViewer);
}
}
catch (Exception e)
{
MessageBox.Show("An error has ocurred. Error: " + e, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Here's a quick example of the ImageViewer Form raising a custom event whenever the checkbox is changed:
public partial class ImageViewer : Form
{
public ImageViewer()
{
InitializeComponent();
}
public delegate void dlgImageChecked(ImageViewer sender, string message);
public event dlgImageChecked ImageChecked;
private void cboxToSave_CheckedChanged(object sender, EventArgs e)
{
if (ImageChecked != null)
{
ImageChecked(this, (cboxToSave.Checked ? "Added: " : "Removed: ") + txFileName.Text);
}
}
}
Now, when you create instances of ImageViewer, you need to wire up that event...something like:
// ... in your MainForm class ...
private void button1_Click(object sender, EventArgs e)
{
// when you create your instances of ImageViewer, wire up their ImageChecked() event:
ImageViewer iv = new ImageViewer();
iv.ImageChecked += Iv_ImageChecked;
}
private void Iv_ImageChecked(ImageViewer sender, string message)
{
ImageViewer iv = (ImageViewer)sender; // if you need to reference it for other reasons ...
stripSelectedFile.Text = message;
txInformation.Text = message;
}
Your original post didn't show the creation of your ImageViewer instances so you'll need to incorporate the above somehow into your code.
I've a txt file with a 360 numbers, I must read all of these and draw a kind of Disc made of FillPie eachone colored in scale of grey due to the value of the list. Until here everything is quite simple.I made a class with the data(value in the txt and degree) of one single fillpie with a Paint method that draw it of the correct color.
this is the code of the class:
class DatoDisco
{
int valoreSpicchio;
int gradi;
public DatoDisco(int valoreTastatore, int gradiLettura)
{
valoreSpicchio = valoreTastatore;
gradi = gradiLettura;
}
public void Clear()
{
valoreSpicchio = 0;
gradi = 0;
}
private int ScalaGrigi()
{
int grigio = 0;
if (valoreSpicchio <= 0)
{
grigio = 125 + (valoreSpicchio / 10);
if (grigio < 0)
grigio = 0;
}
if (valoreSpicchio > 0)
{
grigio = 125 + (valoreSpicchio / 10);
if (grigio > 230)
grigio = 230;
}
return grigio;
}
public void Paint (Graphics grafica)
{
try
{
Brush penna = new SolidBrush(Color.FromArgb(255, ScalaGrigi(), ScalaGrigi(), ScalaGrigi()));
grafica.FillPie(penna, 0, 0, 400, 400, gradi, 1.0f);
}
catch
{
}
}
public int ValoreSpicchio
{
get
{
return valoreSpicchio;
}
}
public int Gradi
{
get
{
return gradi;
}
}
}
here is where I draw everything:
public partial class Samac : Form
{
libnodave.daveOSserialType fds;
libnodave.daveInterface di;
libnodave.daveConnection dc;
int rack = 0;
int slot = 2;
int scalaGrigi = 0;
int angolatura = 0;
List<int> valoriY = new List<int>();
//Disco disco = new Disco();
List<DatoDisco> disco = new List<DatoDisco>();
float[] valoriTastatore = new float[360];
public Samac()
{
InitializeComponent();
StreamReader dataStream = new StreamReader("save.txt");
textBox1.Text = dataStream.ReadLine();
dataStream.Dispose();
for (int i = 0; i <= 360; i++ )
chart1.Series["Series2"].Points.Add(0);
//AggiornaGrafico(textBox1.Text, chart1);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
string indirizzoIpPlc
{
get
{
FileIniDataParser parser = new FileIniDataParser();
IniData settings = parser.LoadFile("config.ini");
return settings["PLC_CONNECTION"]["PLC_IP"];
}
}
private void AggiornaGrafico(string nomeFile, Chart grafico, bool online)
{
int max = 0;
int min = 0;
grafico.Series["Series1"].Points.Clear();
grafico.Series["Series2"].Points.Clear();
grafico.Series["Series3"].Points.Clear();
grafico.Series["Series4"].Points.Clear();
grafico.ChartAreas[0].AxisX.Maximum = 360;
grafico.ChartAreas[0].AxisX.Minimum = 0;
grafico.ChartAreas[0].AxisY.Maximum = 500;
grafico.ChartAreas[0].AxisY.Minimum = -500;
String file = nomeFile;
valoriY.Clear();
disco.Clear();
if (online == false)
{
System.IO.File.WriteAllText("save.txt", nomeFile);
}
StreamReader dataStreamGrafico = new StreamReader(file);
StreamReader dataStreamScheda = new StreamReader("Scheda.sch");
string datasample;
string[] scheda = new string[56];
for (int i = 0; i < 56; i++)
{
scheda[i] = dataStreamScheda.ReadLine();
}
dataStreamScheda.Close();
int gradi = 1;
while ((datasample = dataStreamGrafico.ReadLine()) != null)
{
grafico.Series["Series2"].Points.Add(0);
grafico.Series["Series2"].Color = Color.Red;
grafico.Series["Series2"].BorderWidth = 3;
grafico.Series["Series3"].Points.Add(Convert.ToInt32(float.Parse(scheda[5])));
grafico.Series["Series3"].Color = Color.Green;
grafico.Series["Series3"].BorderWidth = 3;
grafico.Series["Series4"].Points.Add(Convert.ToInt32(-float.Parse(scheda[5])));
grafico.Series["Series4"].Color = Color.Green;
grafico.Series["Series4"].BorderWidth = 3;
grafico.Series["Series1"].Points.Add(int.Parse(datasample));
grafico.Series["Series1"].BorderWidth = 5;
valoriY.Add(int.Parse(datasample));
//disco.Add(int.Parse(datasample));
disco.Add(new DatoDisco(int.Parse(datasample), gradi));
gradi++;
}
dataStreamGrafico.Close();
max = Convert.ToInt32(chart1.Series["Series1"].Points.FindMaxByValue().YValues[0]);
min = Convert.ToInt32(chart1.Series["Series1"].Points.FindMinByValue().YValues[0]);
lblCampanatura.Text = (((float)max + min) / 2000.0).ToString();
lblSbandieramento.Text = (((float)max - min) / 1000.0).ToString();
if ((Math.Abs(max) > 800) || (Math.Abs(min) > 800))
{
if (Math.Abs(max) >= Math.Abs(min))
{
chart1.ChartAreas[0].AxisY.Maximum = max + 200;
chart1.ChartAreas[0].AxisY.Minimum = -(max + 200);
}
else
{
chart1.ChartAreas[0].AxisY.Maximum = min + 200;
chart1.ChartAreas[0].AxisY.Minimum = -(min + 200);
}
}
else
{
chart1.ChartAreas[0].AxisY.Maximum = 800;
chart1.ChartAreas[0].AxisY.Minimum = -800;
}
boxGraficaDisco.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
if (result == DialogResult.OK)
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
ToolTip tooltip = new ToolTip();
private int lastX;
private int lastY;
private void chart1_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
int cursorX = Convert.ToInt32(chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));
tooltip.Show("X:" + cursorX.ToString("0.00") + "Y:" + Convert.ToInt32(chart1.Series[0].Points[cursorX].YValues[0]).ToString(), this.chart1, e.Location.X + 20, e.Location.Y + 20);
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
private void button1_Click_1(object sender, EventArgs e)
{
int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5]))+1;
if (File.Exists(textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt"))
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt";
try
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
catch
{
MessageBox.Show("Il File non esiste");
}
}
else
{
MessageBox.Show("Il File non esiste");
}
}
private void btnGrafMeno_Click(object sender, EventArgs e)
{
int indice = ((int)Char.GetNumericValue(textBox1.Text[textBox1.Text.Length - 5])) - 1;
if (indice >= 0)
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 5) + indice + ".txt";
try
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
catch
{
MessageBox.Show("Il File non esiste");
}
}
else
{
MessageBox.Show("Prima lettura disco");
}
}
private void btnConnetti_Click(object sender, EventArgs e)
{
fds.rfd = libnodave.openSocket(102, indirizzoIpPlc);
fds.wfd = fds.rfd;
if (fds.rfd > 0)
{
di = new libnodave.daveInterface(fds, "IF1", 0, libnodave.daveProtoISOTCP, libnodave.daveSpeed187k);
di.setTimeout(1000000);
dc = new libnodave.daveConnection(di, 0, rack, slot);
int res = dc.connectPLC();
timer1.Start();
// AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
else
{
MessageBox.Show("Impossibile connettersi");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
int res;
res = dc.readBytes(libnodave.daveDB, 21, 40, 1, null);
if (res == 0)
{
var letturaDati = (dc.getS8At(0) & (1 << 0)) != 0;
if (letturaDati == true)
{
int puntatore = 30;
StreamWriter datiDisco = new StreamWriter("DatiDaPlc.csv");
datiDisco.WriteLine("X;" + "C;" + "Z;");
while (puntatore <= 10838)
{
res = dc.readBytes(libnodave.daveDB, 3, puntatore, 192, null);
if (res == 0)
{
for (int i = 0; dc.getU32At(i) != 0; i = i + 12)
{
datiDisco.Write(dc.getU32At(i).ToString() + ";");
datiDisco.Write(dc.getU32At(i + 4).ToString() + ";");
datiDisco.WriteLine(dc.getFloatAt(i + 8).ToString() + ";");
}
}
puntatore = puntatore + 192;
}
datiDisco.Close();
StreamReader lettura = new StreamReader("DatiDaPlc.csv");
StreamWriter scritt = new StreamWriter("Disco.csv");
var titolo = lettura.ReadLine();
var posizioneLettura = lettura.ReadLine();
var posX = posizioneLettura.Split(';');
int minX = Convert.ToInt32(posX[0]) - 5;
int maxX = Convert.ToInt32(posX[0]) + 5;
int contatore = 0;
while (!lettura.EndOfStream)
{
var line = lettura.ReadLine();
var values = line.Split(';');
if ((Convert.ToInt32(values[1]) >= contatore && Convert.ToInt32(values[1]) < contatore + 1000) && (Convert.ToInt32(values[0]) > minX && Convert.ToInt32(values[0]) <= maxX))
{
scritt.WriteLine(Convert.ToInt32(float.Parse(values[2]) * 1000).ToString());
contatore += 1000;
}
}
lettura.Close();
scritt.Close();
AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
}
else
{
timer1.Stop();
MessageBox.Show("Disconnesso");
dc.disconnectPLC();
di.disconnectAdapter();
fds.rfd = libnodave.closeSocket(102);
fds.wfd = fds.rfd;
}
}
}
private void btnDisconnetti_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
dc.disconnectPLC();
di.disconnectAdapter();
fds.rfd = libnodave.closeSocket(102);
fds.wfd = fds.rfd;
timer1.Stop();
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
private void Samac_FormClosing(object sender, FormClosingEventArgs e)
{
if (timer1.Enabled == true)
{
dc.disconnectPLC();
di.disconnectAdapter();
libnodave.closeSocket(102);
timer1.Stop();
}
}
private void button1_Click_2(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
AggiornaGrafico("Disco.csv", chart1, timer1.Enabled);
}
else
{
AggiornaGrafico(textBox1.Text, chart1, timer1.Enabled);
}
}
private void chart2_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
int cursorX = Convert.ToInt32(chart2.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));
int cursorY = Convert.ToInt32(chart2.ChartAreas[0].AxisY.PixelPositionToValue(e.Location.Y));
//tooltip.Show("X:" + chart2.Series[0].Points[cursorX].XValue.ToString() + "Y:" + chart2.Series[0].Points[cursorX].YValues[0].ToString(), this.chart2, e.Location.X + 20, e.Location.Y + 20);
tooltip.Show("X:" + cursorX.ToString() + "Y:#VALY" , this.chart2, e.Location.X + 20, e.Location.Y + 20);
//chart2.Series[0].ToolTip="#VALY";
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
private void boxGraficaDisco_Paint(object sender, PaintEventArgs e)
{
Graphics grafica = e.Graphics;
//disco.Paint(grafica);
foreach (DatoDisco d in disco)
{
d.Paint(grafica);
}
}
private void boxGraficaDisco_MouseMove(object sender, MouseEventArgs e)
{
if (e.X != this.lastX || e.Y != this.lastY)
{
try
{
foreach (DatoDisco d in disco)
{
}
}
catch { }
}
this.lastX = e.X;
this.lastY = e.Y;
}
}
Now I need that when i go with the mouse over the drawn disc, a tooltip show me the data of the fillPie(degree and value of txt) but i can't figure out how.
Anyone can help me?
this is an image of the disc
Eventually it looks as if all you want is a function to get the angle between the mouse position and the center of the disc..
Here is a function to calculate an angle given two points:
double AngleFromPoints(Point pt1, Point pt2)
{
Point P = new Point(pt1.X - pt2.X, pt1.Y - pt2.Y);
double alpha = 0d;
if (P.Y == 0) alpha = P.X > 0 ? 0d : 180d;
else
{
double f = 1d * P.X / (Math.Sqrt(P.X * P.X + P.Y * P.Y));
alpha = Math.Acos(f) * 180d / Math.PI;
if (P.Y > 0) alpha = 360d - alpha;
}
return alpha;
}
I am editing a program made by who knows, a teacher. Anyway, It is to display stock values that are stored in an array shown in a graph. The teacher has noted that the graph Y axis isn't correct, but we don't have to change that. What we have to change is the radio buttons to checkboxes so we can display multiple stock values on a graph.
So to draw the new graph we have to get the minimum and maximum Y values of the stocks selected. I decided to go with:
if (checkBox1.Checked == true)
{
GetStockValues(0);
maxVal[0] = StockArray.Max();
}
int maxValue = Convert.ToInt16(maxVal.Min());
return maxValue;
The same goes for minValue. The problem is I am not getting any correct numbers. Here is the whole program:
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;
namespace VC2008_StockMktGraphics
{
public partial class frmMaster : Form
{
// let's make the stock values array be public so we don't have to pass
// them back and forth.
public double[] StockArray = new double[ 30 ] ;
public double[] minVal = new double [ 4 ];
public double[] maxVal = new double[4];
public frmMaster()
{
InitializeComponent();
}
private void frmMaster_Resize(object sender, EventArgs e)
{
this.Invalidate() ;
}
protected override void OnPaint(PaintEventArgs e)
{
int h = this.Bounds.Height ;
int w = this.Bounds.Width ;
Rectangle r = new Rectangle();
// Create the graphics context to draw into
Graphics gc = this.CreateGraphics() ;
Pen pBl = new Pen( Color.Black , 2) ;
SolidBrush sB = new SolidBrush(Color.Honeydew ) ;
// if the window is too small, force it to a size
if ( ( h < 200 ) || ( w < 200 ) )
{
this.Width = 200 ;
this.Height = 200 ;
}
// Set dynamic location of graphics box
r.X=Convert.ToInt32( Convert.ToDouble( w ) * 0.2 ) ;
r.Y=Convert.ToInt32( Convert.ToDouble( w ) * 0.2 ) ;
r.Width=Convert.ToInt32( Convert.ToDouble( w ) * 0.8 ) -r.X ;
r.Height=Convert.ToInt32( Convert.ToDouble( h ) * 0.8 -r.Y );
// draw the outer rectangle and fill with a light color
gc.DrawRectangle(pBl, r);
gc.FillRectangle(sB, r);
// set the location of the buttons
btnExit.Left = r.X + r.Width + 10;
btnExit.Top = 10;
chkStartAtZero.Left = r.X + r.Width + 10;
chkStartAtZero.Top = btnExit.Top + 25;
checkBox1.Left = r.X + r.Width + 10;
checkBox1.Top = chkStartAtZero.Top + 25;
checkBox2.Left = checkBox1.Left;
checkBox2.Top = checkBox1.Top + 25;
checkBox3.Left = checkBox2.Left;
checkBox3.Top = checkBox2.Top + 25;
checkBox4.Left = checkBox3.Left;
checkBox4.Top = checkBox3.Top + 25;
if (checkBox1.Checked == true)
DrawStock(0, gc, r);
if (checkBox2.Checked == true)
DrawStock(1, gc, r);
if (checkBox3.Checked == true)
DrawStock(2, gc, r);
if (checkBox4.Checked == true)
DrawStock(3, gc, r);
// dispose of object memories we've allocated
pBl.Dispose() ;
sB.Dispose();
gc.Dispose() ;
}
public void DrawStock( int iWhichStock , Graphics gc , Rectangle r )
{
int i ;
int iLabelX;
int iMinY = 999999;
int iMaxY = 0;
int iCnt;
double dxIncrement;
double dyIncrement;
string strAxisLabel;
Point pLineStart = new Point();
Point pLineEnd = new Point();
Pen pB2 = new Pen(Color.Red, 2);
Font f = new Font("Ariel", (float)10.0);
Brush b = new SolidBrush(Color.Blue);
// Normally, we'd get stock from a database, I'm just going to go
// get it from a function with hard-coded values for demonstration
// purposes.
iMinY = Convert.ToInt16(GetMin());
iMaxY = Convert.ToInt16(GetMax());
// Take the min and max to the next increment of 5 outside them.
iMinY = Convert.ToInt16( iMinY / 5 ) * 5 ;
iMaxY = ( Convert.ToInt16(iMaxY / 5 ) + 1 ) * 5 ;
// Find the number of x-coordinate values
iCnt = 0;
foreach (double d in StockArray)
{
if (d > 0)
iCnt++;
}
// so now we know how many x values there are to spread on the x-axis
dxIncrement = Convert.ToDouble(r.Width / iCnt);
// if the zero checkbox is checked, then we'll set the minimums to zero
if (chkStartAtZero.Checked == true)
{
iMinY = 0;
dMinStockValue = 0.0;
}
// so each y-axis pixel must contain this many dollars of actual stock price
dyIncrement = Convert.ToDouble(r.Height / (iMaxY - iMinY));
// set the starting point of the stock line
pLineStart.X = r.X;
pLineStart.Y = r.Top + r.Height -
Convert.ToInt16(dyIncrement * (StockArray[ 0 ] - Convert.ToDouble(iMinY) ) ) ;
// now graph them
for( i = 1 ; i < StockArray.Length ; i++ )
{
if( StockArray[i] == 0 )
continue ;
pLineEnd.X = pLineStart.X + Convert.ToInt16(dxIncrement);
pLineEnd.Y = r.Top + r.Height -
Convert.ToInt16(dyIncrement * (StockArray[i] - Convert.ToDouble(iMinY)));
gc.DrawLine(pB2,pLineStart, pLineEnd ) ;
pLineStart = pLineEnd ;
}
// now draw the y-axis labels
i = iMinY;
pLineStart.X = r.X;
pLineStart.Y = r.Top + r.Height - Convert.ToInt16(0);
pLineEnd.X = r.X - 8;
while( i <= iMaxY )
{
pLineStart.Y = r.Top + r.Height -
Convert.ToInt16( Convert.ToDouble(i-iMinY ) * dyIncrement ) ;
pLineEnd.Y = pLineStart.Y;
gc.DrawLine(pB2, pLineStart, pLineEnd);
strAxisLabel = Convert.ToString(i);
iLabelX = pLineEnd.X - 18;
if (i < 10)
iLabelX = pLineEnd.X - 8;
else
if (i < 100)
iLabelX = pLineEnd.X - 18;
else
if (i < 1000)
iLabelX = pLineEnd.X - 28;
gc.DrawString(strAxisLabel, f, b, iLabelX, pLineEnd.Y - 8);
i += 10;
}
}
public double GetMin()
{
if (checkBox1.Checked == true)
{
GetStockValues(0);
minVal[0] = StockArray.Min();
}
if (checkBox2.Checked == true)
{
GetStockValues(1);
minVal[1] = StockArray.Min();
}
if (checkBox3.Checked == true)
{
GetStockValues(2);
minVal[2] = StockArray.Min();
}
if (checkBox4.Checked == true)
{
GetStockValues(3);
minVal[3] = StockArray.Min();
}
int minValue = Convert.ToInt16(minVal.Min());
label1.Text = Convert.ToString(minValue);
return minValue;
}
public double GetMax()
{
if (checkBox1.Checked == true)
{
GetStockValues(0);
maxVal[0] = StockArray.Max();
}
if (checkBox2.Checked == true)
{
GetStockValues(1);
maxVal[1] = StockArray.Max();
}
if (checkBox3.Checked == true)
{
GetStockValues(2);
maxVal[2] = StockArray.Max();
}
if (checkBox4.Checked == true)
{
GetStockValues(3);
maxVal[3] = StockArray.Max();
}
int maxValue = Convert.ToInt16(maxVal.Min());
label2.Text = Convert.ToString(maxValue);
return maxValue;
}
public void GetStockValues(int iWhichStock)
{
if (iWhichStock == 0)
{
// IBM
StockArray[0] = 147.64; // 1-10-11
StockArray[1] = 147.28;
StockArray[2] = 149.10;
StockArray[3] = 148.82;
StockArray[4] = 150.00;
StockArray[5] = 150.65;
StockArray[6] = 155.69;
StockArray[7] = 155.80;
StockArray[8] = 155.50;
StockArray[9] = 159.63;
StockArray[10] = 161.44;
StockArray[11] = 161.04;
StockArray[12] = 161.07;
StockArray[13] = 159.21;
StockArray[14] = 162.00;
StockArray[15] = 163.56;
StockArray[16] = 163.30;
StockArray[17] = 163.53;
StockArray[18] = 164.00;
StockArray[19] = 164.83;
}
if (iWhichStock == 1)
{
// BA (The Boeing Company)
StockArray[0] = 69.09; // 1-10-11
StockArray[1] = 68.96;
StockArray[2] = 70.15;
StockArray[3] = 69.63;
StockArray[4] = 70.07;
StockArray[5] = 72.47;
StockArray[6] = 71.73;
StockArray[7] = 71.12;
StockArray[8] = 71.68;
StockArray[9] = 72.73;
StockArray[10] = 72.24;
StockArray[11] = 70.02;
StockArray[12] = 70.56;
StockArray[13] = 69.23;
StockArray[14] = 69.48;
StockArray[15] = 70.29;
StockArray[16] = 71.00;
StockArray[17] = 70.98;
StockArray[18] = 71.38;
StockArray[19] = 71.93;
}
if (iWhichStock == 2)
{
// CAP (CAI International
StockArray[0] = 19.44; // 1-10-11
StockArray[1] = 19.66;
StockArray[2] = 19.68;
StockArray[3] = 19.45;
StockArray[4] = 19.79;
StockArray[5] = 19.90;
StockArray[6] = 19.53;
StockArray[7] = 19.06;
StockArray[8] = 19.05;
StockArray[9] = 19.14;
StockArray[10] = 19.28;
StockArray[11] = 20.11;
StockArray[12] = 19.74;
StockArray[13] = 19.06;
StockArray[14] = 19.04;
StockArray[15] = 20.03;
StockArray[16] = 19.69;
StockArray[17] = 19.56;
StockArray[18] = 19.61;
StockArray[19] = 19.63;
}
if (iWhichStock == 3)
{
// TOT (Total Societe Anonyme)
StockArray[0] = 53.00; // 1-10-11
StockArray[1] = 53.32;
StockArray[2] = 55.00;
StockArray[3] = 56.03;
StockArray[4] = 57.11;
StockArray[5] = 57.10;
StockArray[6] = 56.95;
StockArray[7] = 57.12;
StockArray[8] = 57.12;
StockArray[9] = 58.04;
StockArray[10] = 58.79;
StockArray[11] = 58.69;
StockArray[12] = 59.00;
StockArray[13] = 59.50;
StockArray[14] = 57.80;
StockArray[15] = 58.77;
StockArray[16] = 61.03;
StockArray[17] = 60.70;
StockArray[18] = 59.76;
StockArray[19] = 59.25;
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void chkStartAtZero_CheckedChanged(object sender, EventArgs e)
{
this.Invalidate();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
this.Invalidate();
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
this.Invalidate();
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
this.Invalidate();
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
this.Invalidate();
}
private void frmMaster_Load(object sender, EventArgs e)
{
}
}
}
A couple problems.
Your main issue is you call int maxValue = Convert.ToInt16(maxVal.Min()); in GetMax(), I think you wanted int maxValue = Convert.ToInt16(maxVal.Max());.
However once you fix that you are going to run in to the fact that you are comparing uninitialized/old values of the maxVal array.
Say I only have checkbox 1 and 3 checked, then later I un-check 3, What will be the value of maxVal[2] the seccond time GetMax or GetMin is run, (here's a hint, it's not 0)