Programovacie jazyky, rady, poradňa...
Richy
Light Expert
Príspevky: 44 Registrovaný: 07 apr 2011, 18:16
Príspevok
od používateľa Richy » 15 jan 2012, 13:47
Dobrý deň. 1. Chcem sa spýtať že cez C# ako spravím aby sa program spustil automaticky? npr.: Program spustím 1x ja a potom sa bude spúšťať sám.
Kód: Vybrať všetko
procedure SetRunOnStart(AllUsers: Boolean);
var
Registry: TRegistry;
begin
Registry := TRegistry.Create;
with Registry do
try
if AllUsers then
RootKey := HKEY_LOCAL_MACHINE
else
RootKey := HKEY_CURRENT_USER;
if OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Run', False) then
// název položky = titulek aplikace
// hodnota položky = EXE soubor aplikace včetně cesty
WriteString(Application.Title, Application.ExeName)
else
raise Exception.Create('Chyba při otevírání klíče registrů.');
finally
Free;
end;
end;
Čo mám napísať namiesto název položky a hodnota položky? Tento kód zapisuje ten .exe súbor do registrov - myslím si že keby som ten .exe súbor premiestnil niekde inak tak by ho nenašlo.
Tak ak môžem poprosiť aby tento kód hľadal .exe pri sebe a nie inde. Ďakujem.
2. Ako spravím inštaláciu? Vlastne spustím .exe a ono my to nainštaluje do súboru ktorý si tam zadám alebo ho vytvorí.
a) Môže byť aj z tabuľkami.
b) Môže byť aj tak že spustím .exe a len my to ie dotyčné súbory dá kam som to v C# naprogramoval. Ďakujem.
c-ice
Medium Star
Príspevky: 475 Registrovaný: 04 mar 2008, 15:18
Kontaktovať používateľa:
Príspevok
od používateľa c-ice » 15 jan 2012, 14:12
Vo visual studiu si vies vytvorit Setup Projekt a v nom to cele odmanazovat alebo mozes pouzit nejaky 3rd party soft ... ja pouzivam "Inno Setup 5" ... automaticke spustanie pri starte najjednoduchsie vyriesis ze shortcut na EXE vlozis do priecinku %STARTUP%
Richy
Light Expert
Príspevky: 44 Registrovaný: 07 apr 2011, 18:16
Príspevok
od používateľa Richy » 15 jan 2012, 14:15
ok skúsim to tak. Našiel som tento kód je to plánovač úloh / procesov
Kde a čo mám prepísať aby to spúšťalo čo má?
Kód: Vybrať všetko
//Author: Winston Gubantes
//Created: November 26, 2009
//Purpose: to Create or starting a Task by TaskScheduler or By Process
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TaskScheduler;
using System.Windows.Forms;
using System.Diagnostics;
//using System.Runtime.InteropServices; //used to call API windows
namespace BusinessLogic
{
public class TaskHelper
{
public TaskHelper()
{
}
//[DllImport("shell32.dll")]
//private extern int ShellExecute(int hwnd, string operation, string filex, string parameters, string directory, int command);
public static void createTaskImmediateExec(string TaskName, string Comment, string AppName, string Parameters, int SecondsDelay)
{
//Updated By: Winston Gubantes
#region TaskScheduler
TaskScheduler.ScheduledTasks oSt = new TaskScheduler.ScheduledTasks();
TaskScheduler.Task oTask = null;
try
{
oTask = oSt.CreateTask(TaskName);
}
catch (ArgumentException)
{
try
{
//oSt.DeleteTask(“AgentUpdate”);
oSt.DeleteTask(TaskName);
oTask = oSt.CreateTask(TaskName);
}
catch
{
}
}
//oTask.Comment = “MovingPro Agent”;
oTask.Comment = Comment;
//oTask.ApplicationName = “MSIEXEC.EXE”;
oTask.ApplicationName = AppName;
//oTask.WorkingDirectory = Application.StartupPath.Trim();
//oTask.WorkingDirectory = strUpdatePath;
oTask.SetAccountInformation(System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(), (string)null);
//oTask.Parameters = @” /CLEANUP “;
//oTask.Parameters = ” /I ” + strUpdatePath + “\\agentsetup.msi /QN “;
oTask.Parameters = Parameters;
oTask.Flags = TaskFlags.RunOnlyIfLoggedOn;
//oTask.Hidden = true;
if (SecondsDelay > 0)
{
oTask.Triggers.Add(new RunOnceTrigger(DateTime.Now.AddSeconds(SecondsDelay)));
}
oTask.Save();
oTask.Hidden = true;
oTask.Run();
oTask.Close();
oSt.Dispose();
#endregion
}
public static void createTaskOnlogon(string TaskName, string Comment, string AppName, string Parameters)
{
//Updated By: Winston Gubantes
#region TaskScheduler
TaskScheduler.ScheduledTasks oSt = new TaskScheduler.ScheduledTasks();
TaskScheduler.Task oTask = null;
try
{
oTask = oSt.CreateTask(TaskName);
}
catch (ArgumentException)
{
return;
}
//oTask.Comment = “MovingPro Agent”;
oTask.Comment = Comment;
//oTask.ApplicationName = “MSIEXEC.EXE”;
oTask.ApplicationName = AppName;
//oTask.WorkingDirectory = Application.StartupPath.Trim();
//oTask.WorkingDirectory = strUpdatePath;
oTask.SetAccountInformation(System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString(), (string)null);
//oTask.Parameters = @” /CLEANUP “;
//oTask.Parameters = ” /I ” + strUpdatePath + “\\agentsetup.msi /QN “;
oTask.Parameters = Parameters;
oTask.Flags = TaskFlags.RunOnlyIfLoggedOn;
//oTask.Hidden = true;
oTask.Triggers.Add(new OnLogonTrigger());
oTask.Save();
//oTask.Hidden = true;
oTask.Run();
oTask.Close();
oSt.Dispose();
#endregion
}
public static void startProcess(string DirPath, string ExeName, string Arguments)
{
startProcess(DirPath, ExeName, Arguments, false);
}
public static void startProcess(string DirPath, string ExeName, string Arguments,bool isHideWindow)
{
//System.Diagnostics.ProcessStartInfo psi = new ProcessStartInfo();
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = true;
psi.FileName = ExeName;
if (isHideWindow)
{
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.CreateNoWindow = true;
}
if (DirPath != “”) { psi.WorkingDirectory = DirPath; }
psi.Arguments = Arguments;
//psi.Arguments = ” /I ” + @” “”" + strFileName + @” “” ” + ” /QN”;
Process.Start(psi);
}
}
}
//When used in code We used task scheduler for Vista/Win7
BusinessLogic.TaskHelper.createTaskImmediateExec(“Report”,
“Sample Title”,
Application.StartupPath + “\\Your.exe”,
“Sample Args”,
0);
harrison314
Hardcore addict
Príspevky: 8224 Registrovaný: 27 máj 2009, 20:42
Bydlisko: Bratislava
Kontaktovať používateľa:
Príspevok
od používateľa harrison314 » 15 jan 2012, 14:17
mas aj ine moznosti: sfx cez winrar
NSIS
alebo spominane Visualko
// edit: planovac uloh sluzi na daco ine
Richy
Light Expert
Príspevky: 44 Registrovaný: 07 apr 2011, 18:16
Príspevok
od používateľa Richy » 15 jan 2012, 14:35
Tú inštaláciu cez to Visual. Kde nájdem tú funkciu? A k tomu plánovač úloh, načo slúži? Možno by sa my to šiklo.
c-ice
Medium Star
Príspevky: 475 Registrovaný: 04 mar 2008, 15:18
Kontaktovať používateľa:
Príspevok
od používateľa c-ice » 15 jan 2012, 14:55
citaj co pisem v prvych par slovach a skus to chapat ...
Kód: Vybrať všetko
Vo visual studiu si vies vytvorit Setup Projekt
normalne vytvoris projekt z teplatu pre Setup projekt tak ako sa vytvaraju ine projekty ctrl+shift+n... je taka moznost ale zavisi to od visualka ake mas ... pokial mas iba nejake free obmedzene iba na jednu skupinu projektov tak to tam nebudes mat ...
a v tom pripade prave odporucam ten Inno setup je to velmi jednoduche staci si zistit ktore subory k tomu potrebujes dat dokopy a v tom si nastavis vsetky kroky ktore sa maju vykonat
Rovno odpoved na otazku: "Ako zistim co potrebujem pribalit?"
tak ze pouzijes Dependecy Walker a idealne cistu instalaciu Windowsu vo virtualku kde ti to bude hadzat chyby ked to nenajde potrebne DLLko a ty budes vediet ktore chybaju
a dalsia poznámka releasni to projekt prepni na Release lebo Debug mod pridava debug info a je to podstatne vacsie aj Dllky tym usetris miesto cize velkost installacky bude mensia
Richy
Light Expert
Príspevky: 44 Registrovaný: 07 apr 2011, 18:16
Príspevok
od používateľa Richy » 16 jan 2012, 18:01
Už som pochopil. Račej to spravím cez Inno Setup 5. A ten plánovač úloh je načo???
K tomu automatickému spúšťaniu. Našiel som toto, je to projekt vo Visual Studio.
Form1
Kód: Vybrať všetko
namespace StartupFolderShortcut
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonCreate_Click(object sender, EventArgs e)
{
CreateStartupFolderShortcut();
}
private void buttonDelete_Click(object sender, EventArgs e)
{
DeleteStartupFolderShortcuts(Path.GetFileName(Application.ExecutablePath)) ;
}
public void CreateStartupFolderShortcut()
{
WshShellClass wshShell = new WshShellClass();
IWshRuntimeLibrary.IWshShortcut shortcut;
string startUpFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
// Create the shortcut
shortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(startUpFolderPath + "\\" + Application.ProductName + ".lnk");
shortcut.TargetPath = Application.ExecutablePath;
shortcut.WorkingDirectory = Application.StartupPath;
shortcut.Description = "Launch My Application";
// shortcut.IconLocation = Application.StartupPath + @"\App.ico";
shortcut.Save();
}
public string GetShortcutTargetFile(string shortcutFilename)
{
string pathOnly = Path.GetDirectoryName(shortcutFilename);
string filenameOnly = Path.GetFileName(shortcutFilename);
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(pathOnly);
Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
if (folderItem != null)
{
Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
return link.Path;
}
return String.Empty; // Not found
}
public void DeleteStartupFolderShortcuts(string targetExeName)
{
string startUpFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
DirectoryInfo di = new DirectoryInfo(startUpFolderPath);
FileInfo[] files = di.GetFiles("*.lnk");
foreach (FileInfo fi in files)
{
string shortcutTargetFile = GetShortcutTargetFile(fi.FullName);
Console.WriteLine("{0} -> {1}", fi.Name, shortcutTargetFile);
if (shortcutTargetFile.EndsWith(targetExeName, StringComparison.InvariantCultureIgnoreCase))
{
System.IO.File.Delete(fi.FullName);
}
}
}
}
}
Form1.Designer
Kód: Vybrať všetko
namespace StartupFolderShortcut
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.buttonCreate = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// buttonCreate
//
this.buttonCreate.Location = new System.Drawing.Point(12, 12);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(131, 42);
this.buttonCreate.TabIndex = 0;
this.buttonCreate.Text = "Create Shortcut";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.buttonCreate_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(12, 69);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(131, 42);
this.buttonDelete.TabIndex = 1;
this.buttonDelete.Text = "Delete Shortcuts";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.buttonDelete_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(160, 129);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonCreate);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button buttonCreate;
private System.Windows.Forms.Button buttonDelete;
}
}
Tento projekt je bez chyby aj všetko funguje, len ak tieto kódy hodím do 2. projektu tak vyhodí chybu a ani funkcia 1. v tom 2. nejde.
Kód: Vybrať všetko
error CS0104: 'File' is an ambiguous reference between 'System.IO.File' and 'IWshRuntimeLibrary.File'
1. Ako mám spraviť aby mohli byť 2 File v jednej tej zložke? (1. File patrí k niečomu inému a 2. k tomuto.)
2. Ako by sa dalo tieto kódy prerobiť aby to fungovalo cez CheckBox? (odškrtnuté=Create a prázdne=Delete) Ďakujem.
ServerApp
Zablokovaný
Príspevky: 125 Registrovaný: 16 sep 2011, 15:00
Príspevok
od používateľa ServerApp » 16 jan 2012, 19:08
1.) Namiesto "File" zadávaj celé znenie aj s namespace, napr. System.IO.File. Nielen using.
Richy
Light Expert
Príspevky: 44 Registrovaný: 07 apr 2011, 18:16
Príspevok
od používateľa Richy » 16 jan 2012, 19:22
No ale ten File patrí prvému projektu a ten System.IO.File patrí tomu čo som tam pridal a ktorý je vyššie v spojlery.
ServerApp
Zablokovaný
Príspevky: 125 Registrovaný: 16 sep 2011, 15:00
Príspevok
od používateľa ServerApp » 16 jan 2012, 19:33
Komentujem to k tej chybovej hláške. Nenastala by, keby si tam nemal dvakrát v kóde použitý názov triedy "File". Treba to tam doplniť.
Richy
Light Expert
Príspevky: 44 Registrovaný: 07 apr 2011, 18:16
Príspevok
od používateľa Richy » 16 jan 2012, 19:35
Pridal som to tam aj tam a je to bez erroru.
1. Vyriešená. Ďakujem.
Teraz 2.
ServerApp
Zablokovaný
Príspevky: 125 Registrovaný: 16 sep 2011, 15:00
Príspevok
od používateľa ServerApp » 17 jan 2012, 19:50
Navrhujem, aby si uploadol celý projektový adresár v zipku. Bude to tak lepsie.