|
I have a simple question but for someone like me who is not familiar with c# is giving a bit of trouble. I am making a basic script in c# for a bot in a videogame (TERA). What I want is to avoid attacking static immortal debuffs when my character approaches to them. A simple script without nothing would be like this:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace SimpleCombat
{
public class EntryPoint : ZurasBot.Addons.ICombat
{
public override string Name
{
get
{
return "Shell";
}
}
public override void OnLoad()
{
}
public override void OnUnload()
{
}
public override void Settings()
{
}
public override void OnBotStart()
{
}
public override void OnBotStop()
{
}
public override void Patrolling()
{
}
public override Boolean Pull(MyTERA.Helpers.ObjectManager.TERAObject Object)
{
return true;
}
public override Boolean Combat(MyTERA.Helpers.ObjectManager.TERAObject Object)
{
return true;
}
public override void PostCombat()
{
}
}
}
The question is: How/where do I declare/define the pullfunction? What I have to add is this:
if (Object.S1NPCDataController.Name == "name1") return false;
"name1" being the name of the static immortal debuff. Anyone could help me? It is important to me since I am helping a friend to level up his character so he can play with the rest of us! I would really appreciate any help you could give me, it would mean a lot to me! Thank you very much for your help, I hope I can find a solution! Have a nice weekend!
|
|
|
|
|
You'd be better off asking in the forums for the game. You're question has everything to do with the SDK for the game, not C#.
It's VERY unlikely any of the regulars here have written anything for that game.
|
|
|
|
|
Well I don't know the scripting for the game. But if that what you posted is the default BotScript than I would say it should be placed in the "Pull" or "Combat" Method.
ex.:
public override Boolean Pull(MyTERA.Helpers.ObjectManager.TERAObject Object)
{
if(Object != null && Object.S1NPCDataController != null)
return Object.S1NPCDataController.Name != "name1";
return true;
}
|
|
|
|
|
how use nested switch in c#
|
|
|
|
|
int value1 = 2;
int value2 = 6;
switch (value1)
{
case 1: break;
case 2:
switch (value2)
{
case 1: break;
case 2: break;
default: throw new ApplicationException("Unknown value: Value2=" + value2);
}
break;
default: throw new ApplicationException("Unknown value: Value1=" + value1);
}
The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)
|
|
|
|
|
Hello,
I am beginner ( Noob ) in c#,
I am trying to make a small Asset browsing tool for myself, I just wanted to be sure if the way i am going is good or is there a better way to do it.
Currently I have 4 classes
ThumbViewer : extends FlowlayoutPanel
ThumbItem : extends Button
CacheManager.
I have overridden the paint method in the ThumbItem class and painting my Own way.
I also have a Background worker process which reads image file and gets thumbnail out if it and then assigns it to the Image property in the Button.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.ComponentModel;
using System.Drawing.Imaging;
namespace Thumbnailer
{
public class ThumbItem : Button
{
private BackgroundWorker bw;
private string _fullfilename;
private bool _ismouseover = false;
private bool _isSelected = false;
private const int THUMBNAIL_DATA = 0x501B;
private ToolTip _btn_Tooltip;
private bool isDisposed = false;
private bool _itemvisiblecalled = false;
private bool _itemnotvisiblecalled = false;
#region Properties
public string FullName
{
get { return _fullfilename; }
set { _fullfilename = value; }
}
public bool Selected
{
get { return _isSelected; }
set { _isSelected = value; }
}
public Image FileIcon { get; private set; }
public bool isVisible { get; set; }
public string FileName { get; set; }
#endregion
#region Constructor
public ThumbItem()
{
this.Text = "PlaceHolder Thumb";
this.Size = new Size(128, 144);
this.Padding = new Padding(4);
this.BackColor = Color.Transparent;
this.Font = new Font("Verdana", 9, GraphicsUnit.Point);
this.DoubleBuffered = true;
bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(BW_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BW_RunWorkerCompleted);
}
public ThumbItem(string file)
: this()
{
if (!File.Exists(file))
{
throw new FileNotFoundException("Specified file " + file + " doesnt exists.");
}
FileInfo fi = new FileInfo(file);
this.Text = fi.Name.Replace(fi.Extension, "");
this.FileName = fi.Name.Replace(fi.Extension, "");
this.FullName = fi.FullName;
bw.RunWorkerAsync();
}
~ThumbItem()
{
if(!this.isDisposed)
{
bw.DoWork -= BW_DoWork;
bw.RunWorkerCompleted -= BW_RunWorkerCompleted;
this.bw.Dispose();
}
}
#endregion
#region Background Worker
private void BW_DoWork(object sender, DoWorkEventArgs e)
{
if (this._fullfilename != "")
{
Image _thumbimg = null;
Image _icon = null;
FileInfo fi = new FileInfo(this._fullfilename);
if(fi.Extension == ".JPG")
{
using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(this._fullfilename)))
{
using (Image img = Image.FromStream(ms))
{
if (CacheManager<Image>.CurrentInstance.isExists(this.FullName))
{
_thumbimg = CacheManager<Image>.CurrentInstance.GetByKey(this.FullName);
}
else
{
if (img != null)
{
_thumbimg = img.GetThumbnailImage(64, 64, abort_callback, IntPtr.Zero);
CacheManager<Image>.CurrentInstance.Add(this.FullName, _thumbimg);
}
}
}
}
}
else
{
_icon = Icon.ExtractAssociatedIcon(this.FullName).ToBitmap();
}
e.Result = new Image[] { _thumbimg, _icon };
}
}
private void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Image = ((Image[])e.Result)[0];
this.FileIcon = ((Image[])e.Result)[1];
this.Invalidate();
}
#endregion
#region Painting Methods
protected override void OnPaint(PaintEventArgs pevent)
{
Graphics gfx = pevent.Graphics;
StringFormat formatter = new StringFormat();
formatter.LineAlignment = StringAlignment.Center;
formatter.Alignment = StringAlignment.Center;
Rectangle textrect = new Rectangle(0, (this.Height / 2) - (this.FontHeight / 2) - this.Padding.All, this.Width, this.Height);
Color fontcolor = Color.White;
Rectangle parentbounds = this.Parent.Bounds;
if (this.Parent != null)
{
gfx.Clear(this.Parent.BackColor);
}
if (((this.Bounds.Bottom - 10) < this.Parent.Bounds.Top) || (this.Bounds.Top - 10) > this.Parent.Bounds.Bottom)
{
if(!this._itemnotvisiblecalled)
{
ItemNotVisible();
}
}
else
{
if(!this._itemvisiblecalled)
{
ItemVisible();
}
}
if(this.FileName == "IMG_0035")
{
Console.WriteLine("TEmp");
}
if (this.Selected)
{
gfx.FillRectangle(new LinearGradientBrush(this.ClientRectangle, Color.FromArgb(25, 255, 255, 255), Color.FromArgb(150, 255, 255, 255), LinearGradientMode.Vertical), this.ClientRectangle);
}
if (this._ismouseover)
{
gfx.FillRectangle(new LinearGradientBrush(this.ClientRectangle, Color.FromArgb(25, 255, 255, 255), Color.FromArgb(100, 255, 255, 255), LinearGradientMode.Vertical), this.ClientRectangle);
}
Rectangle borderrect = this.ClientRectangle;
ControlPaint.DrawBorder(gfx, borderrect, Color.FromArgb(100, 255, 255, 255), ButtonBorderStyle.Solid);
if (this.Image != null)
{
Rectangle imgrect = new Rectangle(this.Padding.All, this.Padding.All, (this.Width - (this.Padding.All * 2)), (this.Width - (this.Padding.All * 2)));
gfx.DrawImage(this.Image, imgrect);
}
else if (this.FileIcon != null)
{
Rectangle iconrect = new Rectangle(((this.Width / 2) - 16), ((this.Height / 2) - 16), 32, 32);
gfx.DrawImage(this.FileIcon, iconrect);
}
string temp = this.Text;
SizeF textsize = gfx.MeasureString(temp, this.Font);
while (textsize.Width > this.Width / 1.5)
{
temp = temp.Remove(temp.Length - 1);
textsize = gfx.MeasureString(temp, this.Font);
}
temp += "....";
gfx.DrawString(temp, this.Font, new SolidBrush(fontcolor), textrect, formatter);
}
protected override void OnPaintBackground(PaintEventArgs pevent)
{
base.OnPaintBackground(pevent);
}
#endregion
#region Helper Methods
public static Image ResizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.Low;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
public void RefreshThumbnail()
{
this.Image = null;
while(!this.bw.IsBusy)
{
this.bw.RunWorkerAsync();
}
}
private void ItemVisible()
{
this._itemvisiblecalled = true;
this._itemnotvisiblecalled = false;
}
private void ItemNotVisible()
{
this._itemvisiblecalled = false;
this._itemnotvisiblecalled = true;
}
private static bool HasJpegHeader(string filename)
{
using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
{
UInt16 soi = br.ReadUInt16();
UInt16 jfif = br.ReadUInt16();
return soi == 0xd8ff && jfif == 0xe0ff;
}
}
#endregion
#region Event Handlers
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter(e);
this._ismouseover = true;
if ( _btn_Tooltip == null)
{
_btn_Tooltip = new ToolTip();
FileInfo fi = new FileInfo(this.FullName);
string tooltiptext = "";
tooltiptext += "FileName : "+fi.Name+"\n";
tooltiptext += "Path : "+fi.FullName+"\n";
tooltiptext += "Directory : " + fi.DirectoryName + "\n";
_btn_Tooltip.SetToolTip(this, tooltiptext);
}
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
this._ismouseover = false;
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
}
#endregion
#region Event Methods
#endregion
#region UnUsed Methods
private bool abort_callback()
{
return false;
}
#endregion
private void InitializeComponent()
{
this.SuspendLayout();
this.ResumeLayout(false);
}
}
}
Can anyone please tell me if this is the best way to do it, if not then can you please guide me in right direction.
Thanks
Dinesh
|
|
|
|
|
Hi Dinesh,
If you are a "newbie," then, you are at the top of your class: this is a very advanced example using BackgroundWorker, custom Painting, sub-classed WinForms native Controls, etc.
The advanced nature of your code, and the relative lack of comments, or commented-out code, makes me wonder if you wrote this yourself (that's not an accusation !), or if you modified an existing example.
What specific questions, or concerns, do you have about your code ? What happens now, using your code, when you run it, and browse many pictures ? Is the application fast enough under full load to satisfy you ?
The only thing I wonder is: why did you choose to use a Control that inherits from Button, rather than a PictureBox.
It would be interesting to see your CacheManager code, or at least to have a brief description of how you implemented that.
Personally, I have found using the WinForms FlowLayoutPanel very tricky.
yours, Bill
“Humans are amphibians: half spirit, half animal; as spirits they belong to the eternal world; as animals they inhabit time. While their spirit can be directed to an eternal object, their bodies, passions, and imagination are in continual change, for to be in time, means to change. Their nearest approach to constancy is undulation: repeated return to a level from which they repeatedly fall back, a series of troughs and peaks.” C.S. Lewis
|
|
|
|
|
Hello Bill,
First of all thank you for your quick answer I wasn't expecting it, I have never ever got any answer from forums.
Yes everything is not born out of my brain, I took the basic idea and inspiration from
HERE
Using the Background worker is an idea, that I got idea while searching for ways to load images in async way.
Cache Manager concept was cleared by one of my cousin and I wrote my onw. but later on I fond one which was more better so used it.
And that's how I compiled all this, and that is the only reason I am not confident that what i did is right
Is the application fast enough under full load to satisfy you ?
No I am not.
Currently I tried loading 200 Images (each Image of around 6 MB) It takes around 1 Sec to Populate all the items in the Panel, and then around 10-15 secs to display all the Images on the items.
I was expecting it to do everything in less then sec, Am I expecting too much.
What specific questions, or concerns, do you have about your code ?
I wanted to know if there are any optimizations that I can do and I missed,
Also Since I am a newbie I am not pretty sure if I have done everything in correct way.
So as of now these are small questions I have.
Thanks
|
|
|
|
|
Member 8736475 wrote: Currently I tried loading 200 Images (each Image of around 6 MB) It takes around
1 Sec to Populate all the items in the Panel, and then around 10-15 secs to
display all the Images on the items. I was expecting it to do everything in
less then sec, Am I expecting too much.
So you want your HD to come up with 1.2GB worth of data in less than a second? Yeah, you're expecting too much, WAY too much.
To get the illusion of speed you have to cheat a bit. You load only the images you are displaying. If you're got 200 images in a folder, but can only show 10 on screen at a time, you only load the 10 that need to be loaded. The others can wait until either the user scrolls to see them or you can farm those off to a background thread to load.
|
|
|
|
|
Hi Dinesh,
As Dave commented, yes; you are expecting too much to load 1.2 gb. of pictures in under one second. I think even if you had the fastest SSD now available, and tons of RAM, etc., you wouldn't get that performance.
It's a very good practice to study advanced examples that stretch your mind, and challenge you, modify them, tweak them !
As Dave suggested, you probably want to look at "virtualization" if you want to optimize performance. The WinForms ListView Control supports virtualization via the 'VirtualMode Property: [^].
You can also put images in a ListView: [^].
I've never messed around with Images in a ListView, and have no idea how a ListView would perform using virtualization, with a lot of embedded images. Remember that the default .NET Controls are still "wrappers" around very old technology (COM/ActiveX).
Since you have a cache manager, I assume you are storing the thumbnails you generate in it (yes ?). If so, then if you consider (a guess) you are using something around 20k for one 128/144 thumbnail image, then 1200 images results in about 24 megabytes of storage. So, even if you "write-off" the one-time cost of generating the thumbnails, you are probably not going to be able to keep all of them in memory.
I'd consider using another method to contain the grid of images currently shown rather than FlowLayoutPanel, and suggest you substitute using PictureBox for inheriting from Button.
Wish I could be more helpful.
yours, Bill
“Humans are amphibians: half spirit, half animal; as spirits they belong to the eternal world; as animals they inhabit time. While their spirit can be directed to an eternal object, their bodies, passions, and imagination are in continual change, for to be in time, means to change. Their nearest approach to constancy is undulation: repeated return to a level from which they repeatedly fall back, a series of troughs and peaks.” C.S. Lewis
|
|
|
|
|
Hello,
@Bill and @Dave thanks for bringing me to senses.
@Bill : You said you would consider using another method
Can you please guide me in this,
An Ideal common scenario in which this will be used is where there will be no more then 200 Files ( I hope )
And all the files will not be Images, there will be many different file types.
I considered using Control or Picturebox
But in this scenario I noticed that the Scrolling (Using mouse wheel doesnt work), Also the MouseEnter and MouseLeave events are not fired hence I shifted to Button.
Which control / what way do you suggest I substitute the FlowLayoutPanel with.
Thanks
Dinesh,
|
|
|
|
|
Is there a way to make a Form flashing in c#.
First idea is to use a timer changing form color. Is there a more elegant way?
Thanks for your time
|
|
|
|
|
|
Hi, PozzaVecia,
There are two main reasons you might want to make a Form/Window flash: one is to indicate an error message, or something urgently requiring the user's attention. In that case you want to bring the Form to the front, to make sure it's visible. The usual practice, in that case, is to put up a modal Form/Window, which will automatically appear as the frontmost window, and block your application.
You can define a Form, with whatever you want on it, and use FormX.ShowDialog() to display it modally. In many cases, however, the built-in MessageBox facility is all you need to use. Both these objects will automatically become the frontmost window when they are shown.
The second case is when you want to indicate to the end-user that you want them to bring a Form to the front, that's not in front now. But, it's hard for me to see a real reason for doing that:
1. if the Window is covered over by other Windows, the user won't see it change color, or Flash.
Using FlashWindowEx will not make the Window the active window, and bring it frontmost, although the Window will appear to have changed status visually, from inactive to active. MSDN docs for 'FlashWindowEx:
"It does not change the active state of the window."
"When a window flashes, it appears to change from inactive to active status. An inactive caption bar changes to an active caption bar; an active caption bar changes to an inactive caption bar."
In summary:
1. yes, you can make a Window flash, either by using the FlashWindowEx api that Dave K. referred you to, or by writing code, as you mentioned, using a Timer.
2. imho, you should use a modal Form/Window whenever you absolutely must get the end-user's attention, are willing to block the application, and require a response from the user.
3. in most cases, the built-in modal MessageBox facility will give you, for "free," a choice of buttons, default action button, icon, etc.
DialogResult result = MessageBox.Show("Core Melt Down Imminent" ,"Chernobyl Emergency Alert !",MessageBoxButtons.AbortRetryIgnore,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button3);
switch (result.ToString())
{
case "Ignore":
MessageBox.Show("Ignorance is life as usual.");
break;
case "Abort":
MessageBox.Show("To abort is impossible, sorry.");
break;
case "Retry":
MessageBox.Show("Trying again is a waste of time.");
break;
} There are some articles here on CP that may be useful to you: [^].
yours, Bill
“Humans are amphibians: half spirit, half animal; as spirits they belong to the eternal world; as animals they inhabit time. While their spirit can be directed to an eternal object, their bodies, passions, and imagination are in continual change, for to be in time, means to change. Their nearest approach to constancy is undulation: repeated return to a level from which they repeatedly fall back, a series of troughs and peaks.” C.S. Lewis
modified 18-May-13 10:10am.
|
|
|
|
|
very very useful!!!
thanks a lot
|
|
|
|
|
How can I read a the value of a column datatype Timestamp in my c# code?
I know that the timestamp is not a datetime in sql server.
I just want to read this to a byte array.
My code so far:
I have tried 3 variations and none of them even compile.
var myTimestamp = (byte)dr["TimeStamp"].ToString();
var myTimestamp = dr["TimeStamp"].ToString() as byte[];
var myTimestamp = dr["TimeStamp"].ToString();
I have googled and am unable to find it.
Pendin Approval
|
|
|
|
|
Maybe try System.Byte[] myTimestamp = (System.Byte[]) dr["TimeStamp"] ;
|
|
|
|
|
PIEBALDconsult wrote:
Maybe try
System.Byte[] myTimestamp = <br />
(System.Byte[]) dr["TimeStamp"] ;
Thank You. This has now been resolved.
Pendin Approval
|
|
|
|
|
Try reading it as a long.
|
|
|
|
|
That ain't gonna fly. (Unless maybe he casts it on the database side first.)
|
|
|
|
|
Hi to all.
I have a strange behaviour in a MDI project. I created a toolstrip with buttons in MDI parent for common operations in all children forms (New, Save and Delete).
In a child form, I have a DataGridView with a CheckBoxColumn and a TextBoxColumn with a list of options to choose by user. If i check some checkbox and I press the Save button in the toolstrip, I can't save any data: all the checkbox returns false value. But if i put a button in the child form and call the same void, all work very well.
Someone can answer why?
Here the code for button in MDI parent:
private void tsbtnSave_Click(object sender, EventArgs e)
{
if (this.ActiveMdiChild is Basic.AnalyzersCylinders) ((Basic.AnalyzersCylinders)this.ActiveMdiChild).Save();
}
Here the code to read the results:
public void Save()
{
foreach (DataGridViewRow dgRow in dgvAnalyzers.Rows)
{
if (dgRow.Cells["CheckedItem"].Value != null)
{
if ((bool)dgRow.Cells["CheckedItem"].Value)
{
}
else
{
}
}
}
}
And, obviously, the code for the button in Child form call the same Save() void.
|
|
|
|
|
If you put a breakpoint in the save routine and execute your application does it go to debug when you click on the save button?
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
Yes. In the save routine I see the checkedbox items values... but when I press the button in MDI parent, this values are always false, if I press the button in the child form, the values passes in the correct way.
|
|
|
|
|
Hello
Is there a way to extract some values from an XML node using the XmlPathNavigator ?
I need to extrat information from a XML file. I was first trying to use an XmlTextReader but the pure sequential access seeme a bit tedious to handle
So I was trying to use the XpathDocument
I use a XPathNavigator to browse each node of my document (see code below)
But for each product I just need to extract a few information
- Brand
- Model
- ID
(there are a lot of other unneeded information)
Is it possible to do that with the XpathNavigator ?
Or do I need another approach ?
Obviously I can write my own parser but I can't believe that there is no simple way with standard classes ?
Thanks for any help !
XPathDocument xmldoc = new XPathDocument(p);
XPathNavigator nav = xmldoc.CreateNavigator();
int j = 0;
foreach (XPathNavigator product in nav.Select("liste/mobile"))
{
j++;
}
|
|
|
|
|
Probably, but I've never used one. I use an XmlDocument; the SelectNodes and SelectSingleNode methods use XPath.
|
|
|
|
|