Asked by:
c# dll and windows form

Question
-
ok i have a external dll in my program and is it possible to call a function in a separate windows form app so say i have a function in my windows form app i want to get a reverence too in my dll is that at all possible
form1 load
thisisafunction()
dll file
is there a way to call thisisafunction inside a external dll i have made in another project
because you can make a dll and add revrence to that dll in a form and use its functions can the same be applied to a form can you access form functions in a dll ?
All replies
-
If you created the DLL from a Class project in Visual Studio then add a reference to the DLL to the Windows Form project then add a using statement with the namespace of the class project and if there is a sub namespace e.g. MyClassProject.Data as oppose to MyClassProject you need to use the sub namespace. That's it unless I read your question incorrectly.
Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
NuGet BaseConnectionLibrary for database connections.
-
If you created the DLL from a Class project in Visual Studio then add a reference to the DLL to the Windows Form project then add a using statement with the namespace of the class project and if there is a sub namespace e.g. MyClassProject.Data as oppose to MyClassProject you need to use the sub namespace. That's it unless I read your question incorrectly.
Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
NuGet BaseConnectionLibrary for database connections.
nope i have a download function in my dll and i need to call the function in the windows form application witch is a separate project some how or find some way of calling a function each time a if statment is true this is the download funtion in the dll
public void download() { System.IO.Directory.CreateDirectory(elfenliedprogsettings.Read("DOWNLOADPATH") + "/" + displayname); if(Sachiko_Res.Name != string.Empty) { downloadfiles = true; } else { downloadfiles = false; } }
and this is the windows form app seprate project form dll
if(Sachiko_Res.downloadfiles == true) { labelControl4.Text = "Currently Downloading.... " + Sachiko_Res.Name; DownloadFileWithProgress(Sachiko_Res.Url, Sachiko_Res.elfenliedprogsettings.Read("DOWNLOADPATH") + "/" + Sachiko_Res.displayname + "/" + Sachiko_Res.Name, progressBarControl1, labelControl3); } else { XtraMessageBox.Show("Something went wrong.", "error 223"); }
and each time i hit the bool in the dll file i need it to re run this function or need to call the function downloadfile form windows form application some how in the dll so each time it finds and goes to the download function it downloads the new file ( i have like a forloop and it goes though calls download each time but this only loops once so only downloads one image because i cant call the download file form the forum )
thats why i wonder is there any way to make it hit a function multible times each time the forloop iterates though so each time download function is called in dll i need it to revrence the function in the form1 witch are both seprate projects and stand alone
-
If you created the DLL from a Class project in Visual Studio then add a reference to the DLL to the Windows Form project then add a using statement with the namespace of the class project and if there is a sub namespace e.g. MyClassProject.Data as oppose to MyClassProject you need to use the sub namespace. That's it unless I read your question incorrectly.
Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
NuGet BaseConnectionLibrary for database connections.
nope i have a download function in my dll and i need to call the function in the windows form application witch is a separate project some how or find some way of calling a function each time a if statment is true this is the download funtion in the dll
public void download() { System.IO.Directory.CreateDirectory(elfenliedprogsettings.Read("DOWNLOADPATH") + "/" + displayname); if(Sachiko_Res.Name != string.Empty) { downloadfiles = true; } else { downloadfiles = false; } }
and this is the windows form app seprate project form dll
if(Sachiko_Res.downloadfiles == true) { labelControl4.Text = "Currently Downloading.... " + Sachiko_Res.Name; DownloadFileWithProgress(Sachiko_Res.Url, Sachiko_Res.elfenliedprogsettings.Read("DOWNLOADPATH") + "/" + Sachiko_Res.displayname + "/" + Sachiko_Res.Name, progressBarControl1, labelControl3); } else { XtraMessageBox.Show("Something went wrong.", "error 223"); }
and each time i hit the bool in the dll file i need it to re run this function or need to call the function downloadfile form windows form application some how in the dll so each time it finds and goes to the download function it downloads the new file ( i have like a forloop and it goes though calls download each time but this only loops once so only downloads one image because i cant call the download file form the forum )
thats why i wonder is there any way to make it hit a function multible times each time the forloop iterates though so each time download function is called in dll i need it to revrence the function in the form1 witch are both seprate projects and stand alone
Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
NuGet BaseConnectionLibrary for database connections.
-
ok i have a external dll
What kind of DLL? The answer is different depending on whether the DLL is:
- a .Net Class Library
- a COM object or something like that
- the original type of DLL that Windows is built on
- something else; there are many other types of DLLs
Sam Hobbs
SimpleSamples.Info -
Hi elfenliedtopfan2,
Thank you for posting here.
For your question, you want to call a function in windows form in a external dll.
I think you could use reflection to do it.
Here is my test code.
Winforms.
namespace TestWinforms { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void SayHello() { Console.WriteLine("Test"); } } }
dll:
public void Hello() { Assembly assembly = Assembly.LoadFrom(@"D:\TestWinforms.exe"); Type t = assembly.GetType("TestWinforms.Form1"); MethodInfo method=t.GetMethod("SayHello"); var o = Activator.CreateInstance(t); method.Invoke(o, null); }
In console app to call dll method:
static void Main(string[] args) { Test test = new Test(); test.Hello(); Console.ReadKey(); }
Result:
Best Regards,
Jack
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.- Proposed as answer by Kyle Wang - MSFTMicrosoft contingent staff Tuesday, September 17, 2019 7:52 AM
-
that works it allows me to download the files needed :) but only issue i have now is it locks the display im trying to get progress bar to update as the files download would that be possible ? this is the code i am accessing
public void downloadurls() { backgroundWorker1.RunWorkerAsync(); labelControl4.Text = "Currently Downloading.... " + Sachiko_Res.Name; DownloadFileWithProgress(Sachiko_Res.Url, Sachiko_Res.elfenliedprogsettings.Read("DOWNLOADPATH") + "/" + Sachiko_Res.displayname + "/" + Sachiko_Res.Name, progressBarControl1, labelControl3); }
downloadfilewithprogress function
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { DownloadFileWithProgress(Sachiko_Res.Url, Sachiko_Res.elfenliedprogsettings.Read("DOWNLOADPATH") + "/" + Sachiko_Res.displayname + "/" + Sachiko_Res.Name, progressBarControl1, labelControl1); } private void DownloadFileWithProgress(string DownloadLink, string TargetPath, DevExpress.XtraEditors.ProgressBarControl progress, DevExpress.XtraEditors.LabelControl labelProgress) { //Start Download // Function will return the number of bytes processed // to the caller. Initialize to 0 here. int bytesProcessed = 0; // Assign values to these objects here so that they can // be referenced in the finally block Stream remoteStream = null; Stream localStream = null; WebResponse response = null; // Use a try/catch/finally block as both the WebRequest and Stream // classes throw exceptions upon error try { // Create a request for the specified remote file name WebRequest request = WebRequest.Create(DownloadLink); if (request != null) { // Send the request to the server and retrieve the // WebResponse object // Get the Full size of the File double TotalBytesToReceive = 0; var SizewebRequest = HttpWebRequest.Create(new Uri(DownloadLink)); SizewebRequest.Method = "HEAD"; using (var webResponse = SizewebRequest.GetResponse()) { var fileSize = webResponse.Headers.Get("Content-Length"); TotalBytesToReceive = Convert.ToDouble(fileSize); } response = request.GetResponse(); if (response != null) { // Once the WebResponse object has been retrieved, // get the stream object associated with the response's data remoteStream = response.GetResponseStream(); // Create the local file string filePath = TargetPath; localStream = File.Create(filePath); // Allocate a 1k buffer byte[] buffer = new byte[1024]; int bytesRead = 0; // Simple do/while loop to read from stream until // no bytes are returned do { // Read data (up to 1k) from the stream bytesRead = remoteStream.Read(buffer, 0, buffer.Length); // Write the data to the local file localStream.Write(buffer, 0, bytesRead); // Increment total bytes processed bytesProcessed += bytesRead; double bytesIn = double.Parse(bytesProcessed.ToString()); double percentage = bytesIn / TotalBytesToReceive * 100; percentage = Math.Round(percentage, 0); // Safe Update //Increment the progress bar if (progress.InvokeRequired) { progress.PerformStep(); progress.Invoke(new Action(() => progress.Properties.Step = int.Parse(Math.Truncate(percentage).ToString()))); } else { progress.PerformStep(); progress.Properties.Step = int.Parse(Math.Truncate(percentage).ToString()); } //Set the label progress Text if (labelProgress.InvokeRequired) { labelProgress.Invoke(new Action(() => labelProgress.Text = int.Parse(Math.Truncate(percentage).ToString()).ToString())); } else { labelProgress.Text = int.Parse(Math.Truncate(percentage).ToString()).ToString(); } } while (bytesRead > 0); } } } catch (Exception ex) { // Catch any errors } finally { // Close the response and streams objects here // to make sure they're closed even if an exception // is thrown at some point if (response != null) response.Close(); if (remoteStream != null) remoteStream.Close(); if (localStream != null) localStream.Close(); } }
and this is the function i have in dll to get the name and the url and the new updated download method
public void parsetest() { // we grab model files form json file var jsonContent1 = File.ReadAllText(elfenliedprogsettings.Read("DOWNLOADPATH") + "\\textures.json"); var data1 = (JObject)JsonConvert.DeserializeObject(jsonContent1); var texturesNodeKey1 = "/i/models/" + texturemodel; var images1 = new Dictionary<string, string>(); foreach (var resultNode in data1[texturesNodeKey1]["files"]) { var name = resultNode["osgjsUrl"].ToObject<string>(); osjdownload = name; String s = osjdownload; String[] result = s.Split('/'); fileextention = ".osgjs.gz"; string modelbin = "https://media.sketchfab.com/urls/" + result[4] + @"/dist/models/" + result[7]; model_binurl = modelbin; Url = osjdownload; Name = "file"; download(); Name = ""; osjdownload = ""; Url = model_binurl; Name = "model_file"; fileextention = ".bin.gz"; download(); model_binurl = ""; } // start to grab textures var jsonContent = File.ReadAllText(elfenliedprogsettings.Read("DOWNLOADPATH") + "\\textures.json"); var data = (JObject)JsonConvert.DeserializeObject(jsonContent); var texturesNodeKey = "/i/models/" + texturemodel + "/textures?optimized=1"; var images = new Dictionary<string, string>(); foreach (var resultNode in data[texturesNodeKey]["results"]) { var name = resultNode["name"].ToObject<string>(); Name = name; foreach (var imageNode in resultNode["images"]) { var height = imageNode["height"].ToObject<long>(); var width = imageNode["width"].ToObject<long>(); var url = imageNode["url"].ToObject<string>(); Url = url; if (height == 2048 && width == 2048) { //elfenliedtopfan5(); //images.Add(name,url); download(); } } } } public void download() { System.IO.Directory.CreateDirectory(elfenliedprogsettings.Read("DOWNLOADPATH") + "/" + displayname); Assembly assembly = Assembly.LoadFrom(@"C:\Users\elfenliedtopfan5\Desktop\project Sachiko\UpdateTest\bin\Debug\UpdateTest.exe"); Type t = assembly.GetType("UpdateTest.Form1"); MethodInfo method = t.GetMethod("downloadurls"); var o = Activator.CreateInstance(t); method.Invoke(o, null); //if (Sachiko_Res.Name != string.Empty) //{ // downloadfiles = true; //} //else //{ // downloadfiles = false; //} }
-
You're using nouns mixed together here so it seems confusing as to what you're talking about. Supposed you have an application A and a class library L. If you want to call functionality in L from A you would simply add a reference to L from within A's References.
If you want to call functionality in A from L then, technically doable, but not recommended. Extract that shared functionality and put it into L2 (or even L) and then reference that assembly in both A and L.
If you simply want to execute code when something happens then look into delegates or eventing. For example if you have functionality in L that periodically sends update notifications then either have L raise an event that A can listen for or allow A, when it calls the functionality in L, to provide a delegate (function callback) such that L can call it periodically.
Please identify which scenario best meets your needs and perhaps someone can provide a concrete example.
Michael Taylor http://www.michaeltaylorp3.net
-
me explaining how i want it as its too complicated to put into words
i did a video of me doing debuging though it and showing what i want done as i have trouble explain as i have dyslexia
-
Hi elfenliedtopfan2,
Thanks for the feedback.
After watching the video, I understand that your current problem is that your progress bar is not working now.
I think it is different from your initial question. Therefore, I have three suggestions about it.
First, you could mark the useful reply as an answer for your initial question.
Second, you could create a new thread to describe your current question.
Besides, I suggest that you could give a simple code to us or simplify your question so that we could solve your problem in time.
Best Regards,
Jack
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.- Edited by Jack J JunMicrosoft contingent staff, Moderator Monday, September 16, 2019 8:06 AM
- Proposed as answer by Kyle Wang - MSFTMicrosoft contingent staff Tuesday, September 24, 2019 6:20 AM